那么,有哪些问题是 r 值引用无法解决的(完美转发除外,我已经知道了)?
Yes. In order for the swap
trick to work (or at least, work optimally), the class must be designed to be in an empty state when constructed. Imagine a vector
implementation that always reserved a few elements, rather than starting off totally empty. Swapping from such a default-constructed vector
with an already existing vector
would mean doing an extra allocation (in the default constructor of this vector
implementation).
With an actual move, the default-constructed object can have allocated data, but the moved-from object can be left in an unallocated state.
Also, consider this code:
std::unique_ptr<T> make_unique(...) {return std::unique_ptr<T>(new T(...));}
std::unique_ptr<T> unique = make_unique();
This is not possible without language-level move semantics. Why? Because of the second statement. By the standard, this is copy initialization. That, as the name suggests, requires the type to be copyable. And the whole point of unique_ptr
is that it is, well, unique. IE: not copyable.
If move semantics didn't exist, you couldn't return it. Oh yes, you can talk about copy elision and such, but remember: elision is an optimization. A conforming compiler must still detect that the copy constructor exists and is callable; the compiler simply has the option to not call it.
So no, you can't just emulate move semantics with swap
. And quite frankly, even if you could, why would you ever want to?
You have to write swap
implementations yourself. So if you've got a class with 6 members, your swap
function has to swap each member in turn. Recursively through all base classes and such too.
C++11 (though not VC10 or VC2012) allows the compiler to write the move constructors for you.
Yes, there are circumstances where you can get away without it. But they look incredibly hacky, are hard to see why you're doing things that way, and most important of all, make things difficult for both the reader and the writer.
When people want to do something a lot for performance sake that makes their code tedious to read, difficult to write, and error-prone to maintain (add another member to the class without adding it to the swap
function, for example), then you're looking at something that probably should become part of the language. Especially when it's something that the compiler can handle quite easily.