简体   繁体   English

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

[英]Default constructor that calls peer constructor with unique_ptr move

I am trying to make a class with two constructors.我正在尝试使用两个构造函数创建一个类。 One that is a default constructor, the other calling the parameterized constructor.一个是默认构造函数,另一个调用参数化构造函数。 I get a compiler error that tells me that I cannot use move on the object just created and I sort of understand that it doesn't like to do that, because there is no real assignment here.我收到一个编译器错误,告诉我我不能在刚刚创建的对象上使用 move ,我有点理解它不喜欢这样做,因为这里没有真正的赋值。

How can I achieve the right behavior?我怎样才能实现正确的行为? I am trying to avoid writing two constructors that initialize the variables.我试图避免编写两个初始化变量的构造函数。 An initialization function might work, but then I would have to fill the body of the constructors and I was trying to come up with a neat solution like shown below.初始化函数可能会起作用,但随后我必须填充构造函数的主体,并且我试图想出一个简洁的解决方案,如下所示。

#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;
}

main.cpp:18:33: error: invalid initialization of non-const reference of type 'std::unique_ptr&' from an rvalue of type 'std::_MakeUniq::__single_object {aka std::unique_ptr}' Foo() : Foo(make_unique(54)) main.cpp:18:33: 错误:从类型为 'std::_MakeUniq::__single_object {aka std::unique_ptr}' Foo() 的右值对类型为 'std::unique_ptr&' 的非常量引用无效初始化: Foo(make_unique(54))

I decided to go for an rvalue constructor.我决定去寻找一个右值构造函数。 This seems to resolve the issue for me.这似乎为我解决了这个问题。

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM