Reputation: 1689
I have an object something like the following and I'm trying to implement a move constructor for so you can have an insert for std::vector<Mesh>
.
struct Mesh
{
std::vector<Vector3> vPoint;
bool Valid;
Mesh(Mesh&& other)
{
vPoint = std::move(other.vPoint);
Valid = std::move(other.Valid);
}
};
Is this the correct way? And if so what is the value of other.Valid after std::move operates on it?
Edit:
Also if I have an instance of this object do I need to use std::move in the following scenario?
std::vector<Mesh> DoSomething()
{
Mesh mesh; //Imagine vPoint is filled here to
std::vector<Mesh> meshes;
meshes.push_back(std::move(mesh)); // Here is my question, std::move? or just pass mesh here?
return meshes;
}
Upvotes: 12
Views: 19686
Reputation: 109109
You should write your move constructor as follows:
Mesh( Mesh&& other )
: vPoint( std::move( other.vPoint ) )
, Valid( std::move( other.Valid ) )
{}
The disadvantage of assignment within the constructor body as opposed to using the constructor initializer list is that in the former case the member objects of the Mesh
object that you're moving to are default constructed and then assigned to within the body. In the latter case they're constructed directly from the result of the std::move
call.
You shouldn't read from an object, be it an integral type, or a more complex object, after moving it. Such objects exist in an unspecified state.
Upvotes: 15
Reputation: 16253
(partial answer - answering the bit about move
ing bool
)
cppreference.com has the following to say about std::move
:
The library code is required to leave a valid value in the argument, but unless the type or function documents otherwise, there are no other constraints on the resulting argument value. This means that it's generally wisest to avoid using a moved from argument again.
So you cannot rely on a bool
to be either true
or false
after move
ing it.
Upvotes: 3