Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What can be said about the value of fundamental type members of moved from object during move construction?

Consider this code

Foo f1;
Foo f2{ std::move(f1) };

I would expect the member values of f1 to no longer necessarily hold the values given by the default constructor. However, testing with multiple compilers using this implementation of Foo suggests otherwise.

class Foo
{
public:
    Foo() = default;
    Foo(Foo &&) = default;

    std::string s{ "foo" };
    bool t{ true };
    bool f{ false };
};

After the move f1.t is always true and f1.f is always false. As described in this question I would expect the values to either be nondeterministic or that both boolean values would have the same value. However, they seem to get the same value they would get from the default constructor.

Live example with GCC

Is this just a implementation details of my compilers (by coincidence the same) or is this in the standard?

like image 602
Mathias Avatar asked Mar 18 '16 22:03

Mathias


1 Answers

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

For the fundamental types, moving is copying. You wouldn't want your implementation to copy the bool AND zero out the old one - that's unnecessary extra work. In a simple POD, moving would just be a memcpy - but if what you're suggesting would happen, you'd also have to then do a memset. Much faster to just do nothing.

Is this just a implementation details of my compilers (by coincidence the same) or is this in the standard?

This is in the standard in [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.

like image 96
Barry Avatar answered Nov 10 '22 20:11

Barry