WEBINAR:
On-Demand
Building the Right Environment to Support AI, Machine Learning and Deep Learning
The Move Movement and You
The good news is that state-of-the-art STL implementations already use move semantics to optimize swap operations, string concatenation, container reallocation, and many other common operations. Your responsibility as a programmer is to use the specialized
swap() member function of every standard container when possible. Generally speaking:
t.swap(t2)
is more efficient than the generic form:
std::swap(t1, t2)
When designing a new class, consider implementing a swap() member function that uses move semantics. Such a member function is particularly useful if the class in question owns resources that are slow or expensive to copy, such as database connections, GUI elements, and so on.
Start Moving
It's impossible to sign a C++ article these days without a reference to the C++09 standard. C++09 will include a new type of references called rvalue references. Rvalue references are similar to the references you've known for many years, except that they can bind to non-const rvaluesfor example, temporaries. One of the main purposes of adding rvalue references to C++ is streamlining the implementation of move semantics and perfect forwarding. As you've seen, move semantics can be implemented even without rvalue references. However, once rvalue references are incorporated into mainstream C++, moving will become widespread. Expect to hear more about move-constructors (in addition toor instead oftraditional copy-constructors), auto_ptr-style smart pointers, and, overall, an even faster and better C++!