C++中,左值可以取地址,一般也有变量名。
C++里面,右值有两个概念:将亡值和纯右值。
比如:
T&& a = returnVal();
下面是一个例子:
#include <iostream>
#include <string>
void print(std::string&& str) {
std::cout << str << std::endl;
}
int main() {
std::string s1 = "Hello";
std::string s2 = "world";
std::string s3 = s1 + " " + s2;
print(std::move(s3));
return 0;
}
由于 s3 是一个右值, print 函数捕获到这个右值,将其移动进来,而不是被复制。这可以提高程序的性能,因为移动操作比复制操作更快。在 print 函数中,我们只是简单地输出了 str 的值,但实际上我们可以对它进行任何操作,就像它是一个普通的 std::string 对象一样。
No comments yet.