展会信息港展会大全

c++怎样让返回对象的函数不调用拷贝构造函数
来源:互联网   发布日期:2016-01-19 13:00:13   浏览:1814次  

导读:我们知道拷贝构造函数有两种默默的方式被调用1 想函数传入 值参数2 函数返回 值类型今天我们讨论函数返回值类型的情况。得到结论是1 当对象有拷贝构造函数(系统为我们生成、或者我们自己写拷贝构造函数 ...

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

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 t" <<&thing.member_ << endl;

return thing;//会调用到拷贝构造函数

}

unique_ptr<int> getBySmartPtr()

{

unique_ptr<int> p(new int);

cout << "in method t" << *p << endl;//注意unique_ptr已经重载了*操作符,实际输出的是裸指针的内存地址

return p;//会调用unique_ptr move构造函数

}

void main()

{

Thing th= getThingByReturnValue();

cout << "out method t" << &th.member_ << endl;

auto p = getBySmartPtr();

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

}

/*

in method003CF798

copy

out method003CF88C//可见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 method003EFC18

move

out method003EFD0C

in method-842150451

out method-842150451

请按任意键继续. . .

*/

赞助本站

人工智能实验室
相关内容
AiLab云推荐
展开

热门栏目HotCates

Copyright © 2010-2024 AiLab Team. 人工智能实验室 版权所有    关于我们 | 联系我们 | 广告服务 | 公司动态 | 免责声明 | 隐私条款 | 工作机会 | 展会港