使用移动调用对等构造函数unique_ptr默认构造函数



我正在尝试创建一个具有两个构造函数的类。一个是默认构造函数,另一个调用参数化构造函数。我收到一个编译器错误,告诉我我不能在刚刚创建的对象上使用 move,我有点明白它不喜欢这样做,因为这里没有真正的赋值。

如何实现正确的行为?我试图避免编写两个初始化变量的构造函数。初始化函数可能会起作用,但随后我必须填充构造函数的主体,并且我试图提出如下所示的简洁解决方案。

#include <string>
#include <iostream>
#include <memory>
using namespace std;
class Foo
{
public:
Foo(unique_ptr<int>& number) : m_number(move(number))
{
}
Foo() : Foo(make_unique<int>(54))
{
}
void print()
{
cout << m_number << endl;
}
private:
unique_ptr<int> m_number;
};
int main()
{
Foo f;
f.print();
return 0;
}

主.cpp:18:33:错误:非常量引用的初始化无效 类型"std::unique_ptr&",来自类型的右值 'std::_MakeUniq::__single_object {aka std::unique_ptr}' Foo(( : Foo(make_unique(54((

我决定使用右值构造函数。这似乎为我解决了问题。

#include <string>
#include <iostream>
#include <memory>
using namespace std;
class Foo
{
public:
// rvalue constructor so that we can move the unique_ptr.
Foo(unique_ptr<int>&& number) : m_number(move(number))
{
}
Foo() : Foo(make_unique<int>(54))
{
}
void print()
{
cout << *m_number << endl;
}
private:
unique_ptr<int> m_number;
};
int main()
{
Foo f;
f.print();
unique_ptr<int> a = make_unique<int>(33);
Foo f2(move(a)); // important to do a move here, because we need an rvalue.
f2.print();

return 0;
}

最新更新