lvalue,rvalue及rvalue reference
lvalue及rvalue
摘自Understanding the meaning of lvalues and rvalues in C++:
In C++ an lvalue is something that points to a specific memory location.
On the other hand, a rvalue is something that doesn't point anywhere.
In general, rvalues are temporary and short lived, while lvalues live a longer life since they exist as variables.
It's also fun to think of lvalues as containers and rvalues as things contained in the containers.
lvalue
佔據了記憶體空間,壽命較長,可以將它想像為容器。
rvalue
並未指向記憶體的任何地方,是暫時的,可以將它想像為容器裡的東西。
rvalue reference
rvalue
是暫時的,無法被修改。
而C++0x新引入的rvalue reference
則讓使用者有修改rvalue
的能力。
以下範例摘自C++ rvalue references and move semantics for beginners:
std::string s1 = "Hello ";
std::string s2 = "world";
std::string&& s_rref = s1 + s2; // the result of s1 + s2 is an rvalue
s_rref += ", my friend"; // I can change the temporary string!
std::cout << s_rref << '\n'; // prints "Hello world, my friend"
s1 + s2
的返回值本來是rvalue
,是無法被更改的。但是這裡定義了一個std::string&&
型別的變數,std::string
後面的&&
使得它可以指向s1 + s2
這個暫存物件(指向右值,即右值引用,rvalue reference)。有了rvalue reference,我們就可以修改它所指向的暫存物件,因此 s_rref += ", my friend";
才可以執行成功。