0

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.

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))

1
  • 5
    Why is this a (normal) reference? You're stealing someones unique_ptr without permission. Make it a rvalue reference. Commented Jan 30, 2020 at 10:47

1 Answer 1

0

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.