C++ 智能指针 unique_ptr 不可拷贝的例外情况,“可拷贝或赋值一个将要被销毁的unique_ptr”

16 篇文章 1 订阅

书上的例子是这样的:

我们可以拷贝或赋值一个将要被销毁的unique _ptr。最常见的例子是从函数返回一个unique_ptr
如下面代码所示:

unique_ptr<int> clone(int p)
{
	return unique_ptr<int>(new int(p));
}

还可以返回一个局部对象的拷贝:

unique_ptr<int> clone(int n)
{
	unique_ptr<int> ret(new int(p));
	return ret;
}

书上的解释:

在这里插入图片描述

我的疑问:

  • 这里到底是如何触发的 移动构造函数?不是需要传入右值吗?难道即将被销毁的unique_ptr就是右值了??好奇怪。
  • 所有马上就要被销毁的对象,作为返回值被返回时,都会触发移动构造吗??对于这个问题,我做了个实验。

对于第二个问题的实验:

我用一个类模拟了一下,上面返回unique_ptr的两个函数,并测试其输出结果。

Test.h文件:

#pragma once
#ifndef _TEST_H_
#define _TEST_H_
#include<memory>
#include<string>
#include<iostream>

using namespace std;

class Test
{
public:
	Test() : p(nullptr) { }
	Test(Test&&) noexcept ;
	Test(Test&);
	Test(int n) : p(new int(n)) { }
	Test& operator=(const Test&);
	Test& operator=(Test&&) noexcept ;
	~Test();
private:
	int* p;
};

#endif

Test.cpp文件:

#include "Test.h"

Test::Test(Test&& t) noexcept : p(t.p)
{
	cout << "调用移动构造函数" << endl;
	t.p = nullptr;
}

Test::Test(Test& t) : p(new int(*t.p)) { cout << "调用拷贝构造函数" << endl; }

Test& Test::operator=(const Test& t)
{
	if (this != &t)
	{
		delete p;
		p = new int(*t.p);
	}
	return *this;
}

Test& Test::operator=(Test&& t) noexcept
{
	if (this != &t)
	{
		p = t.p;
		t.p = nullptr;
	}
	return *this;
}

Test::~Test() { delete p; }

main.cpp文件一:

#include<iostream>
#include"Test.h"

Test aaa(int x)
{
	cout << "111" << endl;
	return Test(x);
}

Test bbb(int x)
{
	Test t(x);
	return t;
}

int main()
{
	Test t = aaa(1);
	t = bbb(1);
	return 0;
}

输出结果:
在这里插入图片描述
结果表明:只有bbb函数的返回值会调用移动构造,但还是不知道为什么会这样。。。

目前,我直接把这个当作unique_ptr的一个特性死记硬背了。

真的是整不明白了,欢迎各位看到这里的大佬和我讨论这个问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

phyit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值