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

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

问题描述

标准定义了一个对象一旦被移动就可以做什么?我以前认为,所有你可以做的一个移动对象是做破坏它,但这是不够的。

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?)

推荐答案

移动对象存在于未指定但有效的状态中。这表明虽然对象可能不再能够做很多了,它的所有成员函数应该仍然显示定义的行为—包括 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) code>,所以如果移动构造函数(或复制构造函数,如果没有提供移动)是显式函数将失败。

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天全站免登陆