什么是左值及右值
左值是为可以引用的值,能够取到内存地址。
右值是不可取到内存地址的值,是一个临时值。
什么是右值引用
左值有左值引用,较为常见。如果想对右值进行引用,则需要使用右值引用。
int get_value(){
return 5;
}
int & lvalue = get_value(); // error
const int& lvalue = get_value(); // 不能修改其值
int&& r_reference = get_value(); // 右值引用,并且可以后续修改值
为什么需要使用右值引用
例如使用vector压入值时,会产生两次构造, 这回造成资源浪费。
// Create am object of Container and return
Container getContainer()
{
Container obj;
return obj;
}
std::vector<Container> vecOfContainers;
vecOfContainers.push_back(getContainer()); // 创造了两次obj,第一次getContainer使用默认构造函数构造. 第二次拷贝发生在vector push时调用了拷贝构造函数产生obj。
怎样只构造一次
使用move constructor
重载构造函数,输入为右值引用
Container(Container && obj)
{
// Just copy the pointer
m_Data = obj.m_Data;
// Set the passed object's member to NULL
obj.m_Data = NULL;
std::cout<<"Move Constructor"<<std::endl;
}