*
“If you’re an experienced C++ programmer and are anything like me, you initially approached C++11 thinking, “Yes, yes, I get it. It’s C++, only more so.” But as you learned more, you were surprised by the scope of the changes. auto declarations, range-based for loops, lambda expressions, and rvalue references change the face of C++, to say nothing of the new concurrency features. And then there are the idiomatic changes. 0 and typedefs are out, nullptr and alias
declarations are in. Enums should now be scoped. Smart pointers are now preferable to built-in ones. Moving objects is normally better than copying them.
- Effective Modern C++ by Scott Meyers*
*
这是大牛在Effective Modern C++中的一段对新C++特性的总结。其中rvalue references是一个比较核心的改进,对某些情况下对C++代码的效率很有帮助。最近在看相关的文档,笔者想写篇关于rvalue references的介绍性文章;准备分两部分:第一部分介绍下什么是rvalue和rvalue references,第二部分介绍它的应用。
lvalue 和 rvalue
lvalue和rvalue的概念最初来自C语言,后来C++对它们有所扩展。最初,在C里lvalue和rvalue貌似分别指一个赋值表达式的左边和右边值。(“L” stands for “left” and “R” stands for “right“)C++引入后,这个名字里左边啊,右边啊,就变得不那么清晰了;也就是C++里它们不再局限于赋值表达式的左边和右边了。
首先,有一点是肯定的,C++里一个表达式要么是lvalue的,要么是rvalue。这里有一点要强调,lvalue和rvalue的是表达式的属性,不是object的属性。(C++03 3.10/1 says: “Every expression is either an lvalue or an rvalue.”)
lvalue一般是有可以寻址的存储位置&#x