qubits
qubits

Reputation: 1307

How to obtain polymorphic behavior with unique pointers?

Playing around with C++ after a longer break.

I have a std::vector of unique pointers to objects through which I iterate, calling a function that takes as argument the base class from which the objects in the vector are derived, like so:

for (auto const& object : objects)
{
    _process(object);
}

where objects would be:

std::vector<std::unique_ptr<Derived>>

I would like to understand how would I enforce polymorphic behavior to call the function:

_process(std::unique_ptr<Base> base)

Upvotes: 0

Views: 583

Answers (1)

Ap31
Ap31

Reputation: 3314

std::unique_ptr represents ownership, and therefore can not be copied.

That means that _process(std::unique_ptr<Base> base) is a sink, i.e. it consumes the object (it can destroy it or store it somewhere, but the caller has no control over it anymore). In order to call it you'd have to use std::move:

_process(std::move(object))

that way you explicitly reject the ownership over the object and essentially remove it from your container - the pointer will be reset to nullptr.

Naturally that can only be done via non-const reference.

If you don't want to transfer the ownership and just want to do something with the object - which the name _process seem to imply - you're supposed to pass the regular raw pointer:

_process(Base* base);
...
for (auto const& object : objects)
{
    _process(object.get());
}

Raw pointers are still great for everything except controlling the lifetime of your objects.

In both cases (raw pointer and unique_ptr) there should be absolutely no problem with implicitly converting from Derived to Base.

Upvotes: 3

Related Questions