临时变量与复制构造函数
来源:互联网 发布:狄仁杰魔术师皮肤优化 编辑:程序博客网 时间:2024/06/05 23:34
class B{public:B(){cout << "构造函数" << endl;}B(const B &b){cout << "复制构造函数" << endl;}~B(){cout << "析构函数" << endl;}};B play(B b){return b;}
main函数输入如下代码:
{B b1;play(b1);}输出:
main函数输入如下代码:
{B b1;B b2=play(b1);}
输出:
为什么两个图是一样的?我猜是因为B b2=play(b1); 这一行代码,通过复制构造函数产生了临时返回值变量,然后b2调用了移动复制构造函数?
做一下实验,加入赋值操作符和移动构造函数:
<pre name="code" class="cpp">class B{public:B(){cout << "构造函数" << endl;}B(const B &b){cout << "复制构造函数" << endl;}B(B &&b){cout << "移动构造函数" << endl;}B& operator=(const B &b){cout << "赋值操作符" << endl;if (this == &b)return *this;return *this;}~B(){cout << "析构函数" << endl;}};B play(B b){return b;}void main(){{B b1;B b2 = play(b1);}cout << "-------------------------" << endl;{B b1;B b2;b2 = play(b1);}}
输出:
去掉移动构造函数:
class B { public: B(){ cout << "构造函数" << endl; } B(const B &b) { cout << "复制构造函数" << endl; } B& operator=(const B &b) { cout << "赋值操作符" << endl; if (this == &b) return *this; return *this; } ~B() { cout << "析构函数" << endl; } }; B play(B b) { return b; } void main() { { B b1; B b2; b2 = play(b1); } }
输出:
0 0
- 临时变量与复制构造函数
- 临时变量与复制构造函数(二)
- 复制构造函数和隐式转换 ---临时变量问题
- c++类临时对象、复制构造函数、析构函数 VS2017 与gcc 编译器对比
- c++ 赋值构造函数 临时变量 临时对象 之一
- 复制构造函数与赋值构造函数
- 复制构造函数与赋值构造函数
- 复制构造函数与拷贝构造函数
- 构造函数与复制构造函数
- 关于构造函数与复制构造函数
- 临时对象与拷贝构造函数
- 临时对象与拷贝构造函数
- C++13.1 复制构造函数-----临时对象(不是很懂)
- 临时变量调用拷贝构造函数的次数
- 复制构造函数 与 赋值操作函数
- 拷贝构造函数 与拷贝复制函数
- 重载赋值函数与复制构造函数
- 临时对象的(构造函数与析构函数)
- hbase down机 重启zookeeper 解决的异常
- ORA-19909: datafile 1 belongs to an orphan incarnation 一例
- linux 命令系列之 history(41)
- Android GPU加速实现图像颜色传递(Color transfer)
- android比较好的博客
- 临时变量与复制构造函数
- linux 命令系列之 alias 和 bash快捷键(42)
- Map容器(hash_map)
- 媒体曝光社保系统漏洞,数千万社保用户信息或泄露
- 关于云服务怎么玩
- 仿快图系统自带图片浏览器应用源码项目
- tomcat添加到系统服务,提供启动脚本
- ListView的Item中设置Button点击事件优化,避免重复new Listener
- IOS开源APP应用