C++程序设计方法3:移动构造函数

移动拷贝构造函数

语法:

ClassName(ClassName&&);

目的:

用来偷“临时变量”中的资源(比如内存)

临时变量被编译器设置为常量形式,使用拷贝构造函数无法将资源偷出来(“偷”是对原来对象的一种改动,违反常量的限制)

基于“右值引用“定义的移动构造函数支持接受临时变量,能偷出临时变量中的资源;

#include <iostream>
using namespace std; class Test
{
public:
int *buf;//only for demo
Test()
{
buf = new int();
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 ;
}

//备注:编译器对返回值做了优化,因此增加编译选项,禁止编译器进行返回值的优化
/*
g++ wo2.cpp --std=c++11 -fno-elide-constructors
*/

上一篇:CentOS7/6 关闭防火墙


下一篇:CentOS7 防火墙(firewall)的操作命令