2 ms·
std::move on vector zeroes out the source element array. e.g. (pseudo-ish code) operator=(vector&& foo) { delete [] elements; elements = foo.elements; foo.
by olliej 8y ago
std::move on vector zeroes out the source element array.
e.g. (pseudo-ish code)
operator=(vector&& foo) {
delete [] elements;
elements = foo.elements;
foo.elements = nullptr;
}
what the example code they have as an answer does is something morally equivalent to this:
operator=(vector&& foo) {
swap(elements, foo.elements);'
}
relying on the knowledge that because it's being moved the ~vector is going to be called immediately afterwards.
This strikes me as being "clever" in the "potentially confusing code, for no real reason" sense
- gpderetta 8y agoactually that move assignment operator is not ideal. The foo parameter won't be destroyed immediately but only at the end of whatever scope (if any) it was at the call site. The idiomatic copy and swap is like this: T& operator =(T x) // note pass by value { std::swap(this, x); return this; } This acts both as a normal and move assignment operator (if T is not copy constructible); edit: how do you get HN to show asterisks? There should be one before each 'this'
- arh68 8y agoPrefix each line with 4 spaces: T& operator =(T x) // note pass by value { std::swap(*this, x); return *this; }