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 int
s have to be copied one by one?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With