std::shared_ptr
has a nifty templated constructor that automagically creates the right deleter for its given type (constructor #2 in that link).
Until just now, I (erroneously) thought std::unique_ptr
had a similar constructor, but when I ran the following code:
#include <memory>
#include <iostream>
// Notice nothing is virtual
struct Foo
{
~Foo() { std::cout << "Foo\n"; }
};
struct Bar : public Foo
{
~Bar() { std::cout << "Bar\n"; }
};
int main()
{
{
std::cout << "shared_ptr:\n";
std::shared_ptr<Foo> p(new Bar()); // prints Bar Foo
}
{
std::cout << "unique_ptr:\n";
std::unique_ptr<Foo> p(new Bar()); // prints Foo
}
}
I was surprised to learn that unique_ptr
doesn't call Bar
's destructor.
What's a clean, simple, and correct way to create a unique_ptr
that has the correct deleter for its given pointer? Especially if I want to store a whole list of these (i.e. std::vector<std::unique_ptr<Foo>>
), which means that they all must have a heterogeneous type?
(pardon the poor title; feel free to suggest a better one)