Short Version: You don't want a dynamic pointer to a collection of Base
; you want a collection of dynamic pointer-to-Base
.
You seem to be misunderstanding where to place std::unique_ptr
in your polymorphic collection. It isn't the collection that needs to be pointers for polymorphism to work; it's the object held within.
For example:
#include <iostream>
#include <vector>
#include <memory>
struct Base
{
virtual ~Base() {}
virtual void foo() const = 0;
};
class DerivedOne : public Base
{
public:
virtual void foo() const
{
std::cout << "DerivedOne\n";
}
};
class DerivedTwo : public Base
{
public:
virtual void foo() const
{
std::cout << "DerivedTwo\n";
}
};
int main()
{
std::vector< std::unique_ptr<Base> > objs;
objs.emplace_back(std::make_unique<DerivedOne>());
objs.emplace_back(std::make_unique<DerivedTwo>());
// via operator[]
objs[0]->foo();
objs[1]->foo();
// via range-for
for (auto const& p : objs)
p->foo();
// via iterators
for (auto it = objs.begin(); it !=objs.end(); ++it)
(*it)->foo();
}
Output
DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
DerivedOne
DerivedTwo
Whether you want the collection itself to be managed dynamically via a smart pointer is unrelated (and somewhat questionable) to this issue.