Rvalue reference
By chys on June 28th, 2009The new feature in C++0x was rather confusing to me until yesterday when I suddenly realized that my codes could be more efficient if we had rvalue references.
In my understanding, the main practical use of rvalue references is to eliminate spurious copies by introducing a “move” semantics in addition to the existing “copy” semantics.
Suppose we have a map object: map<int,SomeComplexType> my_map;
The most intuitive statement to add something to it is my_map[key] = value;.
In current C++, a copy assignment must be triggered here, potentially unnecessary and expensive. (“Copy” semantics.)
If value will not be used later (esp. it’s a temporary object), we may want to “move” instead of “copy” it into the map. (“Move” semantics.)
[Sure, we can use value.swap (my_map[key]); if swapping is efficient (e.g. STL strings & containers). But this is rather unreadable.]
In C++0x, with rvalue references, we can distinguish them easily:
- Use "copy" semantics in
SomeComplexType::operator = (const SomeComplexType &); - Use "move" semantics in
SomeComplexType::operator = (SomeComplexType &&);(Should we call it a "move assignment"?)
Now the compiler automatically chooses between the "copy" or "move" semantics for my_map[key] = value;, depending on whether value is an rvalue or not.
It is also possible to force the "move" semantics: my_map[key] = std::move (value);
What std::move does is accept either an lvalue or rvalue reference, and return it as an rvalue reference.
Microsoft Visual C++ supports, as a non-standard extension, binding temporary objects to non-const (lvalue) references. This extension cannot substitute rvalue references:
string a = "Hello";
string b = a;
If we use move semantics in string::string (string &), then a will be empty after b's construction. This usually is not what we desire.
Again, my main concern about C++0x is that it's going to be too complicated to learn.
Reference:
A Brief Introduction to Rvalue References
Related posts:
