书上的例子是这样的:
我们可以拷贝或赋值一个将要被销毁的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
的一个特性死记硬背了。