Denis Gladkiy
Denis Gladkiy

Reputation: 2174

Why move constructor does not called without std::move?

I've got this code:

SomeType::SomeType(std::vector<Item>&& container, const float someOtherPArameter)
    : internal_container(std::move(container))
{
    // some code here
}

Can somebody explain to me why a move constructor does not call for the 'internal_container' without 'std::move'?

Upvotes: 2

Views: 123

Answers (2)

user3920237
user3920237

Reputation:

The move constructor is called whenever an object is initialized from xvalue of the same type. You can create that xvalue by calling std::move(x). Declaring a parameter as an rvalue reference will not automatically make it an xvalue.

Upvotes: 2

Ben Voigt
Ben Voigt

Reputation: 283614

Because

SomeType::SomeType(std::vector<Item>&& container, const float someOtherPArameter)
    : internal_container(container)
{
    // the parameter container is in scope here
}

It would be pretty surprising if, inside the constructor body, accesses to the parameter container found a moved-from object. (It would also break code that was perfectly valid in C++03)

That's why you have to explicitly enable move.

Upvotes: 2

Related Questions