我可以用移出的对象做什么? [英] What can I do with a moved-from object?

查看:47
本文介绍了我可以用移出的对象做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该标准是否准确定义了一个对象一旦被移出后我可以对它做什么?我曾经认为你可以对移动对象做的所有事情就是破坏它,但这还不够.

Does the standard define precisely what I can do with an object once it has been moved from? I used to think that all you can do with a moved-from object is do destruct it, but that would not be sufficient.

以标准库中定义的函数模板swap为例:

For example, take the function template swap as defined in the standard library:

template <typename T>
void swap(T& a, T& b)
{
    T c = std::move(a); // line 1
    a = std::move(b);   // line 2: assignment to moved-from object!
    b = std::move(c);   // line 3: assignment to moved-from object!
}

显然,必须可以分配给已移动的对象,否则第 2 行和第 3 行将失败.那么我还能对移动的对象做什么呢?在标准中我究竟在哪里可以找到这些细节?

Obviously, it must be possible to assign to moved-from objects, otherwise lines 2 and 3 would fail. So what else can I do with moved-from objects? Where exactly can I find these details in the standard?

(顺便问一下,为什么是 T c = std::move(a); 而不是 T c(std::move(a));在第 1 行?)

(By the way, why is it T c = std::move(a); instead of T c(std::move(a)); in line 1?)

推荐答案

Moved-from 对象存在于未指定但有效的状态.这表明虽然该对象可能无法再做很多事情,但它的所有成员函数仍应表现出已定义的行为 —包括 operator= —以及它的所有成员都处于一个定义的状态——它仍然需要销毁.该标准没有给出具体定义,因为它对于每个 UDT 都是唯一的,但您可能能够找到标准类型的规范.有些像容器比较明显——他们只是移动他们的内容,一个空容器是一个定义明确的有效状态.基元不会修改移出的对象.

Moved-from objects exist in an unspecified, but valid, state. That suggests that whilst the object might not be capable of doing much anymore, all of its member functions should still exhibit defined behaviour — including operator= — and all its members in a defined state- and it still requires destruction. The Standard gives no specific definitions because it would be unique to each UDT, but you might be able to find specifications for Standard types. Some like containers are relatively obvious — they just move their contents around and an empty container is a well-defined valid state. Primitives don't modify the moved-from object.

旁注:我相信它是 T c = std::move(a) 因此,如果移动构造函数(或复制构造函数,如果没有提供移动)是显式的,则函数将失败.

Side note: I believe it's T c = std::move(a) so that if the move constructor (or copy constructor if no move is provided) is explicit the function will fail.

这篇关于我可以用移出的对象做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆