考虑这段代码
Foo f1;
Foo f2{ std::move(f1) };
我希望 f1
的成员值不再一定包含默认构造函数给出的值。但是,使用 Foo
的这种实现对多个编译器进行的测试表明情况并非如此。
class Foo
{
public:
Foo() = default;
Foo(Foo &&) = default;
std::string s{ "foo" };
bool t{ true };
bool f{ false };
};
move 后 f1.t
始终为 true
而 f1.f
始终为 false
。如 this question 中所述 我希望这些值要么是不确定的,要么两个 bool 值具有相同的值。但是,它们似乎获得了与默认构造函数相同的值。
这只是我的编译器的实现细节(碰巧相同)还是这在标准中?
最佳答案
After the move
f1.t
is alwaystrue
andf1.f
is alwaysfalse
.
对于基本类型, move 就是复制。您不希望您的实现将 bool AND 复制为旧的清零 - 这是不必要的额外工作。在一个简单的 POD 中, move 只是一个 memcpy
- 但如果你的建议发生了,那么你还必须执行一个 memset
。什么都不做要快得多。
Is this just a implementation details of my compilers (by coincidence the same) or is this in the standard?
这在[class.copy] 中的标准中:
The implicitly-defined copy/move assignment operator for a non-union class X performs memberwise copy- /move assignment of its subobjects. [...] Each subobject is assigned in the manner appropriate to its type:
— [...]
— if the subobject is of scalar type, the built-in assignment operator is used.
关于c++ - 在 move 构造过程中,从对象 move 的基本类型成员的值可以说些什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36095290/