“右值引用”的补充说明
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
相关文章推荐
- 关于“幽灵架构”的补充说明3:为什么不会产生“循环引用”
- 对C++中引用的补充说明
- 对C++中引用的补充说明
- [转载]对C++中引用的补充说明(实例)
- JavaScript 值和引用、构造函数和函数直接量的补充说明
- 对C++中引用的补充说明(实例)
- [教程]JScript中的变量引用规则(补充,函数用法说明)
- 战30天C++入门极限-对C++中引用的补充说明(实例一)
- 挑战30天C++入门极限-对C++中引用的补充说明(实例三)
- 战30天C++入门极限-对C++中引用的补充说明(实例二)
- C++11 标准新特性: 右值引用与转移语义
- C++11尝鲜:右值引用和转发型引用
- 类模板相互引用的问题(错误:缺少类型说明符-假定为int。注意:C++不支持默认int)
- C++ 11 右值引用的理解
- C++11新特性: 右值引用 和 右值语义(rvalue sematics)
- 中国移动EMPP v2.0 协议补充说明
- (BUG已修改,最优化)安卓ListView异步加载网络图片与缓存软引用图片,线程池,只加载当前屏之说明
- 无聊的细节:指针、引用、右值
- 从4行代码看右值引用
- 引用初始化、左值右值、函数数组参数