Reputation: 75150
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?
Upvotes: 22
Views: 3551
Reputation: 477640
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.
Upvotes: 21