您的位置:首页 > 其它

“右值引用”的补充说明

2014-09-24 11:26 232 查看
#include "stdafx.h"
#include <string>
#include <iostream>
/*
Title:“右值引用”的补充说明
Env:VS2013Update3
Author:Kaugla!
Date:2014-09-24
Desc:能用&运算符取得地址的是lvalue类型,反之为rvalue类型。
Note:
[1]std::move,仅仅是lvalue类型转rvalue类型, 这样你才能调用源的move constructor或move assignment operator!
如果源有const修饰,虽然调用std::move不会throw exception,但是不会调用源的move constructor和move assignment operator。
[2]const T getT(); // makes the move constructor useless, the temporary is const!
[3]一旦定义了move constructor,编译器就不会为你默认生成其它constructor! move assignment operator同理。
*/
class SimplestClass
{
public:
// move constructor
//源没有const修饰符,可修改源属性。
SimplestClass(SimplestClass&& other)
: _name(std::move(other._name))
{
//如果有裸指针_p_vals属性, 在这里assignment _p_vals to dest, 然后置源_p_vals属性为NULL。
//源_p_vals属性不为NULL,源(可能是临时对象)释放的时候,会调用析构函数释放_p_vals指向的内存块。
}

// copy constructor
//注意const修饰符,源属性不能修改。//here 没有std::move!
SimplestClass(const SimplestClass& other): _name(other._name)	{
//如果源是const T&类型
//虽然可以调用std::move,不会throw exception!
//但是也不会调用std::string的move assignment operator!
}

//non-parameter constructor
//定义了一个constructor后,其它constructor编译器不会为你默认生成了!
//需要无参constructor的话得自己写一个
SimplestClass()	{ _name = "default"; }

//普通assignment operator
//有const修饰,无法修改源属性。
void operator = (SimplestClass const& s)
{
//如果源是T const&类型
//虽然可以调用std::move,不会throw exception!
//但是也不会调用std::string的move assignment operator!
_name = s._name;
}

//move assignment operator
//无const修饰,可以修改源属性
//如果没有定义move assignment operator就会调用普通assignment operator如果有的话!
void operator = (SimplestClass && s)
{
_name = std::move(s._name);
}

void operator = (std::string && s)
{
_name = std::move(s);
}
private:
std::string _name;
};

int _tmain(int argc, _TCHAR* argv[])
{
//About assignment operator
SimplestClass sc;
sc = std::string("abc");//调用move assignment operator如果有的话。
sc = SimplestClass();//调用move assignment operator如果有的话。
//如果你没有定义move assignment constructor, 就是sc = std::move(SimplestClass());也是调用普通的constructor!
SimplestClass sc2;
sc2 = sc;//调用普通assignment operator.因为sc不是rvalue类型。

//About constructor
SimplestClass sc3(sc2);//调用了普通构造函数
SimplestClass sc4(std::move(sc2));//调用move constructor!

//input any key to continue...
std::cin.get();
return 0;
}//end func
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: