c++怎样让返回对象的函数不调用拷贝构造函数

我们知道拷贝构造函数有两种“默默”的方式被调用

1. 想函数传入 值参数

2. 函数返回 值类型

今天我们讨论函数返回值类型的情况。

得到结论是

1. 当对象有拷贝构造函数(系统为我们生成、或者我们自己写拷贝构造函数)可以被隐式调用时,函数返回时会使用拷贝构造函数。

2. 当对象的拷贝构造函数声明成为explicit(不能被隐式调用时),函数返回时会使用move构造函数。

先看开始的代码。

#include <iostream>
#include <memory>
using namespace std;

class Thing{

public:
	int		member_;

	Thing():member_(0){  //默认构造函数
	}

	Thing(Thing& other):member_(other.member_){//拷贝构造函数
			cout << "copy" << endl;
	}
	
	Thing(Thing&& other):member_(other.member_){//move构造函数
		cout << "move" << endl;
	}
};

Thing getThingByReturnValue()
{
	Thing thing;
	thing.member_ = 1;
	cout << "in method 	" <<  &thing.member_ << endl;
	return thing;//会调用到拷贝构造函数
}

unique_ptr<int> getBySmartPtr()
{
	unique_ptr<int> p(new int);
	cout << "in method 	" << *p << endl;//注意unique_ptr已经重载了*操作符,实际输出的是裸指针的内存地址
	return p;//会调用unique_ptr move构造函数
}

void main()
{
	Thing th  = getThingByReturnValue();
	cout << "out method 	" << &th.member_ << endl;

	auto p = getBySmartPtr();
	cout << "out method 	" << *p << endl;//注意unique_ptr已经重载了*操作符,实际输出的是裸指针的内存地址
}

/*
in method       003CF798
copy
out method      003CF88C  //可见getThingByReturnValue调用的是Thing的copy构造函数
in method       -842150451
out method      -842150451  //可见getBySmartPtr调用的是unique_ptr的move构造函数
请按任意键继续. . .
*/


为什么我们写的类会调用copy,而unique_ptr会调用move??百思不得其解。。睡觉时想到了,explicit修饰构造函数的用法。给拷贝构造函数加上explicit试试。

explicit Thing(Thing& other):member_(other.member_){//拷贝构造函数
	cout << "copy" << endl;
}

/*
in method       003EFC18
move
out method      003EFD0C
in method       -842150451
out method      -842150451
请按任意键继续. . .
*/


哈哈,copy->move!!

原文地址:https://www.cnblogs.com/keanuyaoo/p/3320050.html