c++ - 在 move 构造过程中,从对象 move 的基本类型成员的值可以说些什么?

标签 c++ c++11 language-lawyer move-semantics

考虑这段代码

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 始终为 truef1.f 始终为 false。如 this question 中所述 我希望这些值要么是不确定的,要么两个 bool 值具有相同的值。但是,它们似乎获得了与默认构造函数相同的值。

Live example with GCC

这只是我的编译器的实现细节(碰巧相同)还是这在标准中?

最佳答案

After the move f1.t is always true and f1.f is always false.

对于基本类型, 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/

相关文章:

c++ - 如何在一个表达式中生成并返回结果?

c - if语句中的单独声明?

c - 指针相等是否意味着整数相等?

c++ - g++ 的严格别名警告准确性

c++ - 属性编辑器的设计模式?

c++ - Visual Studio 包含来自其他项目的 cpp 文件

c++ - 为什么 std::is_move_constructible<S>::value == false 尽管 S move 构造很好?什么是正确的行为?

lambda - C++0x 闭包的未定义行为 : II

c++ - 是否应该将整数值传递给浮点用户定义的文字?

android - 奇怪的 "stutter"在不同的 android 设备上的 box2D