Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.Pointer Container made obsolete by std::unique_ptr in C++11/14?

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?

like image 946
Mr.C64 Avatar asked Jul 15 '13 15:07

Mr.C64


3 Answers

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>>.

like image 74
Praetorian Avatar answered Sep 21 '22 07:09

Praetorian


It's not obslete; it has a completely different and more intuitive interface than std::vector<std::unique_ptr<T>>.

like image 20
James Kanze Avatar answered Sep 17 '22 07:09

James Kanze


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.

like image 35
xinnjie Avatar answered Sep 21 '22 07:09

xinnjie