Since 2011, we have both copy and move assignment. However, this answer argues quite convincingly that, for resource managing classes, one needs only one assignment operator. For std::vector
, for example, this would look like
vector& vector::operator=(vector other)
{
swap(other);
return*this;
}
The important point here is that the argument is taken by value. This means that at the moment the function body proper is entered, much of the work has already been done by the construction of other
(by move constructor if possible, otherwise by copy constructor). Hence, this automatically implements both copy and move assignment correctly.
If this is correct, why is (according to this documentation at least) std::vector
not implemented in this way?
edit to explain how this works. Consider what happens to other
in above code in the following examples
void foo(std::vector<bar> &&x)
{
auto y=x; // other is copy constructed
auto z=std::move(x); // other is move constructed, no copy is ever made.
// ...
}
std::vector
assignment provides the strong exception guarantee I think an allocation is needed anyway. – Centenarianstd::string
(which itself manages resources). – Nicolasstd::vector
s. If that is the case, then the extra assignment involved in copy and swap can be avoided. But I have to go and check if this is really the case. – Centenarian