Does std::unique_ptr
make Boost.Pointer Container library obsolete in C++11/14?
In C++98/03 there isn't move semantics, and a smart pointer like shared_ptr
has reference-counting related overhead (both for the ref counting block, and the interlocked increment/decrements) if compared to raw pointers. So something like std::vector<shared_ptr<T>>
has overhead if compared to std::vector<T*>
.
But is std::vector<std::unqiue_ptr<T>>
just as efficient as std::vector<T*>
(no reference counting overhead), and in addition safe in regard to exceptions and automatic destruction (i.e. vector<unique_ptr<T>>
destructor will automatically call the destructors for the T
items whose pointers are stored in the vector
)?
If so, does Boost.Pointer Container still have a valid useful place in C++11/14 code, or is it just obsolete?
As James mentions in his answer, the Boost.Pointer containers offer a more intuitive interface as compared to what you get by sticking a unique_ptr
into a standard library container.
Aside from that, boost::ptr_vector<T>
(and friends) store the pointed to type as a void *
underneath, so you don't get an entire class template instantiation for every T
. This is not the case with vector<unique_ptr<T>>
.
It's not obslete; it has a completely different and more
intuitive interface than std::vector<std::unique_ptr<T>>
.
try to use std::vector<std::unqiue_ptr<T>>
struct Foo {
int a;
};
vector<unique_ptr<Foo>> bar;
bar.push_back(make_unique<Foo>(1));
cout << bar[0]->a << endl; // rvalue, is ok
Foo *foo = bar[1].get(); // try to use a pointer, this interface "bar[1].get()" is awful
Boost.Pointer Container certainly has more intuitive interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With