Move semantics should not be thought as an optimization device, even if they can be used as such.
If you are going to want copies of objects (either function parameters or return values), then RVO and copy elision will do the job when they can. Move semantics can help, but are more powerful than that.
Move semantics are handy when you want to do something different whether the passed object is a temporary (it then binds to a rvalue reference) or a "standard" object with a name (a so called const lvalue). If you want for instance to steal the resources of a temporary object, then you want move semantics (example: you can steal the contents a std::unique_ptr
points to).
Move semantics allow you to return non copyable objects from functions, which is not possible with the current standard. Also, non copyable objects can be put inside other objects, and those objects will automatically be movable if the contained objects are.
Non copyable objects are great, since they don't force you to implement an error-prone copy constructor. A lot of the time, copy semantics do not really make sense, but move semantics do (think about it).
This also enables you to use movable std::vector<T>
classes even if T
is non copyable. The std::unique_ptr
class template is also a great tool when dealing with non copyable objects (eg. polymorphic objects).
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…