MOOC清华《面向对象程序设计》第3章:移动构造函数实验

来源:互联网 发布:网络歌曲女生唱的 编辑:程序博客网 时间:2024/05/21 23:34

#include <iostream>using namespace std;class Test{public:int* buf;  //only for demo Test(){buf = new int(3);cout << "Test():this->buf@" << hex << buf << endl;}~Test(){cout << "~Test():this->buf@" << hex << buf << endl;if(buf) delete buf;}Test(const Test& t):buf(new int(*t.buf)){cout << "Test(const Test&) called. this->buf@" << hex << buf << endl;}Test(Test&& t):buf(t.buf){cout << "Test(Test&&) called. this->buf@" << hex << buf << endl;t.buf = nullptr;}};Test GetTemp(){Test tmp;cout << "GetTemp():tmp.buf@" << hex << tmp.buf << endl;return tmp; }void fun(Test t){cout << "fun(Test t):t.buf@" << hex << t.buf << endl;}int main(){Test a = GetTemp();cout << "main():a.buf@" << hex << a.buf << endl;fun(a);return 0;}

当编译选项只有 -std=c++11 时的运行结果:


可见移动构造函数并没有被调用。原因是编译器自动做了返回值优化。需要增加一条编译选项:-fno-elide-constructors ,见下图(Dev C++ 5.11):



当这条编译选项也被加进去之后,再次编译运行,结果如下:


可以看见移动构造函数已经被调用。


若在源代码中去掉移动构造函数,而编译选项依然是上述两条语句时,编译运行结果为:


发现拷贝构造函数顶替了移动构造函数的调用位置,但是拷贝构造函数中 buf 的地址并不是GetTemp()函数中 buf 的地址。也就是说 临时变量 tmp 的值并没有被保存下来,由此可见移动构造函数的独特作用,是拷贝构造函数代替不了的。

阅读全文
0 0