1

Here's a simple piece of code. What I want help with is the two places I've writen "???".

The goal is to pass a temporary pointer to the container-class which then becomes the unique owner of that object. However, I do not know what to write in the two places where I've writen "???".

In particular, what do I write in the initializer-list, and what do I write when I actually instantiate my container-class?

class abstractBase
{
    virtual void method() = 0;
};

class derived : public abstractBase
{
    // ...
};

class container
{
    std::unique_ptr<abstractBase> ptr;
    container(std::unique<abstractBase> input)
        : ??? //What do I write here to make input = ptr?
    {}
};

int main()
{
container instance(???) //what do I write here to pass a temporary ptr of type derived?
}

For the first one, I thought maybe

: ptr(std::move(input))

would be the way?

For the second one, I am not sure. Maybe just std::make_unique<derived> input?

Swapnil
  • 1,424
  • 2
  • 19
  • 30
Ieao
  • 23
  • 2
  • I'd recommend a virtual destructor for abstractBase. https://stackoverflow.com/questions/274626/what-is-object-slicing – Kenny Ostrom Sep 22 '18 at 16:58

1 Answers1

4

Yes, std::move and std::make_unique should do the trick here:

class container
{
    std::unique_ptr<abstractBase> ptr;

public:
    container(std::unique_ptr<abstractBase> input)
        : ptr(std::move(input))
    {}
};

int main()
{
    container instance(std::make_unique<derived>());
}

You might also wanna have a look at this article concerning sink parameters and move-only types.

Michael Kenzel
  • 15,508
  • 2
  • 30
  • 39