Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move Constructor, move vector between two objects using std::move?

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;
}
like image 728
NtscCobalt Avatar asked Feb 09 '13 01:02

NtscCobalt


People also ask

Does std::vector use move constructor?

Managing Resources with std::vector When writing a class that manages vectors, we don't have to specifically write move constructor and move assignment operator because std::vector has implemented it for us. Look at the following example: In our Data class, we only implement a default constructor and that's it.

What does std :: move () do?

std::move is used to indicate that an object t may be "moved from", i.e. allowing the efficient transfer of resources from t to another object. In particular, std::move produces an xvalue expression that identifies its argument t . It is exactly equivalent to a static_cast to an rvalue reference type.

How do you move one vector to another?

You can't move elements from one vector to another the way you are thinking about; you will always have to erase the element positions from the first vector. If you want to change all the elements from the first vector into the second and vice versa you can use swap.

What does move () do in C++?

std::move() is a function used to convert an lvalue reference into the rvalue reference. Used to move the resources from a source object i.e. for efficient transfer of resources from one object to another.


1 Answers

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.

like image 86
Praetorian Avatar answered Oct 11 '22 13:10

Praetorian