现在的位置: 首页 > 综合 > 正文

C++11 右值引用

2018年04月13日 ⁄ 综合 ⁄ 共 997字 ⁄ 字号 评论关闭

右值引用 (Rvalue Referene) 是 C++ 新标准 (C++11, 11 代表 2011 年 ) 中引入的新特性 , 它实现了转移语义 (Move Sementics)
和精确传递 (Perfect Forwarding)。它的主要目的有两个方面:

  1. 消除两个对象交互时不必要的对象拷贝,节省运算存储资源,提高效率。
  2. 能够更简洁明确地定义泛型函数。
1.右值引用
 int a;
 a = 1; // here, a is an lvalue
上述的a就是一个左值。
C++11中左值的声明符号为”&”,为了和左值区分,右值的声明符号为”&&”
printReference (const String& str)
{
cout << str;
}
printReference (String&& str)
{
cout << str;
}
string me( "alex" );
printReference( me ); // 调用第一函数,参数为左值常量引用
printReference(   "alex"  ); 调用第二个函数,参数为右值引用。
#include <iostream>
void process_value(int& i)
{ 
	std::cout << "LValue processed: " << i << std::endl; 
} 
void process_value(int&& i) 
{ 
	std::cout << "RValue processed: " << i << std::endl; 
}        
int main() 
{ 
	int a = 0; 
	process_value(a); 
	process_value(1);
	return 0;
}
运行结果 :
LValue processed: 0
RValue processed: 1
例2:
void process_value(int& i)
{ 
    std::cout << "LValue processed: " << i << std::endl; 
} 
void process_value(int&& i)
{ 
	std::cout << "RValue processed: " << i << std::endl; 
}
void forward_value(int&& i)
{ 
	process_value(i); 
} 
int main() 
{ 
	int a = 0; 
	process_value(a); 
	process_value(1); 
	forward_value(2); 
	return 0;
}
运行结果:
LValue processed: 0 
RValue processed: 1
LValue processed: 2



抱歉!评论已关闭.