C++ lvalue,rvalue及rvalue reference

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";才可以執行成功。

參考連結

Understanding the meaning of lvalues and rvalues in C++

C++ rvalue references and move semantics for beginners

发布了90 篇原创文章 · 获赞 9 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/keineahnung2345/article/details/104074624