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); } }
输出:
原文地址:http://blog.csdn.net/bupt8846/article/details/45217099