在移动构造过程中,从对象移动的基本类型成员的值可以说些什么?
What can be said about the value of fundamental type members of moved from object during move construction?
考虑这段代码
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 };
};
移动后 f1.t
总是 true
而 f1.f
总是 false
。如 this question 中所述,我希望这些值要么是不确定的,要么两个布尔值具有相同的值。但是,它们似乎获得了与默认构造函数相同的值。
这只是我的编译器的实现细节(巧合的是相同的)还是这在标准中吗?
After the move f1.t
is always true
and f1.f
is always false
.
对于基本类型,移动就是复制。您不希望您的实现复制 bool AND 将旧的清零 - 这是不必要的额外工作。在一个简单的 POD 中,移动只是 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.
考虑这段代码
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 };
};
移动后 f1.t
总是 true
而 f1.f
总是 false
。如 this question 中所述,我希望这些值要么是不确定的,要么两个布尔值具有相同的值。但是,它们似乎获得了与默认构造函数相同的值。
这只是我的编译器的实现细节(巧合的是相同的)还是这在标准中吗?
After the move
f1.t
is alwaystrue
andf1.f
is alwaysfalse
.
对于基本类型,移动就是复制。您不希望您的实现复制 bool AND 将旧的清零 - 这是不必要的额外工作。在一个简单的 POD 中,移动只是 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.