What can I do with a moved-from object?(我可以用移出的对象做什么?)
问题描述
该标准是否准确定义了一个对象一旦被移出后我可以对它做什么?我曾经认为你可以对移动对象做的所有事情就是破坏它,但这还不够.
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.
这篇关于我可以用移出的对象做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我可以用移出的对象做什么?
基础教程推荐
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 设计字符串本地化的最佳方法 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01