Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move-semantics with a member std::vector

Tags:

Sorry if this has been asked before, but as I understand it, in C++11, std::vector has a move constructor so that copies cost hardly anything in certain situations, like returning one by value. However, if I have a class like this, with a vector as a member variable:

class MyClass {
public:
    MyClass() { }
    MyClass(const MyClass& rhs) { }

    // other interfaces

private:
    std::vector<int> myvec;

    // implementation
};

And have a function which returns one of these by value, such as

MyClass somefunc() {
    MyClass mc;
    // fill mc.myvec with thousands (maybe even millions) of ints
    return mc;
}

Will the move constructor of mc.myvec be called and the move constructor of std::vector taken advantage of even though MyClass itself doesn't know anything about move constructors? Or will the copy constructor of vector be called and all those thousands (maybe even millions) of ints have to be copied one by one?

like image 622
Seth Carnegie Avatar asked Nov 24 '11 04:11

Seth Carnegie


People also ask

Does STD Vector have a move constructor?

No. It doesn't call the move constructor. To call move constructor of element you will have to call std::move while pushing to vector itself.

How do I move an element from one vector to another in C++?

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. @R.

What happens when you std :: move a vector?

std::move. 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.

What does move () do in C ++?

std::move in C++Moves the elements in the range [first,last] into the range beginning at result. The value of the elements in the [first,last] is transferred to the elements pointed by result. After the call, the elements in the range [first,last] are left in an unspecified but valid state.


1 Answers

If you don't write any explicit copy or move constructors or any copy or move assignment operators or a destructor, then the default-provided move-constructor moves elements one-by-one. For details, see 12.8.9.

Since you define your own copy constructor, you will not get a move constructor by default. Either define one (perhaps = default), or get rid of the explicit copy constructor.

Well-composed classes shouldn't usually need any custom Big Five, and instead rely on members providing them and use the default version.

like image 100
Kerrek SB Avatar answered Oct 25 '22 17:10

Kerrek SB