C++:对于哪些对象,"moved" 意味着比 "staying valid" 多?
C++: For which objects, being "moved" implies more than "staying valid"?
鉴于 a
和 b
属于 T
类型,我们有移动构造 (T b(move(a));
) 或移动赋值 (b = move(a)
) .在什么情况下我们知道 a
的值是多少?
我唯一确定的是unique_ptr
,其中a
将成为一个空指针。这也保证 shared_ptr
吗?是否还有其他 类 标准保证已知值?
标准库类型
根据标准 N4296,§17.6.3.1,让我们 rv
成为 T
类型的右值,
在 Table 20,MoveConstructible 要求和 Table 22 MoveAssignable 要求中。
运算后:
T(rv);
T u =rv;
u = rv;
rv’s state is unspecified [ Note:rv must still meet the requirements of the library component that is using it. The operations listed in those requirements must work as specified
whether rv has been moved from or not. — end note ]
这意味着至少您移动的对象仍然处于有效状态并且可以用作其类型的任何对象。但作为图书馆范围的要求,仅此而已。您必须阅读特定的文档。
对于 shared_ptr 特别是:
shared_ptr(shared_ptr&& r) noexcept;
template<class Y> shared_ptr(shared_ptr<Y>&& r) noexcept;
Remark: The second constructor shall not participate in overload resolution unless Y* is convertible
to T*.
Effects: Move-constructs a shared_ptr instance from r.
Postconditions: *this shall contain the old value of r. r shall be empty. r.get() == nullptr.
基本类型和普通可复制对象
移动的对象应该没有变化。我正在寻找标准中的确认...
其他类型
至少 class 的程序员应该确保这个 class 的对象在移动后是可破坏的!
鉴于 a
和 b
属于 T
类型,我们有移动构造 (T b(move(a));
) 或移动赋值 (b = move(a)
) .在什么情况下我们知道 a
的值是多少?
我唯一确定的是unique_ptr
,其中a
将成为一个空指针。这也保证 shared_ptr
吗?是否还有其他 类 标准保证已知值?
标准库类型
根据标准 N4296,§17.6.3.1,让我们 rv
成为 T
类型的右值,
在 Table 20,MoveConstructible 要求和 Table 22 MoveAssignable 要求中。
运算后:
T(rv);
T u =rv;
u = rv;
rv’s state is unspecified [ Note:rv must still meet the requirements of the library component that is using it. The operations listed in those requirements must work as specified whether rv has been moved from or not. — end note ]
这意味着至少您移动的对象仍然处于有效状态并且可以用作其类型的任何对象。但作为图书馆范围的要求,仅此而已。您必须阅读特定的文档。
对于 shared_ptr 特别是:
shared_ptr(shared_ptr&& r) noexcept;
template<class Y> shared_ptr(shared_ptr<Y>&& r) noexcept;
Remark: The second constructor shall not participate in overload resolution unless Y* is convertible to T*.
Effects: Move-constructs a shared_ptr instance from r. Postconditions: *this shall contain the old value of r. r shall be empty. r.get() == nullptr.
基本类型和普通可复制对象
移动的对象应该没有变化。我正在寻找标准中的确认...
其他类型
至少 class 的程序员应该确保这个 class 的对象在移动后是可破坏的!