Reputation: 143
Does MyType have to be "movable" for the compiler to be able to apply move semantics when returning v from foo()?
std::vector<MyType> foo() {
std::vector<MyType> v;
// populate v
return v;
}
Upvotes: 1
Views: 81
Reputation: 180710
No, vector does not need your type to be moveable in order for the vector itself to be moveable. Essentially a vector is
template <typename T>
class vector
{
private:
T* start;
T* end;
T* capcity_end;
public:
...
vector(vector&& old) : start(old.start), end(old.end), capcity_end(old.capcity_end) {
old.start = old.end = old.capcity_end = nullptr;
}
...
};
And when the vector moves, it just copies the pointer values into the new vector, and sets to pointers to nullptr
in the old vector so that they do not get cleaned up by the destructor. With this, T
doesn't even need to be copyable, as no elements are being copied/moved, it's just pointers getting swapped.
Upvotes: 3