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

倖福魔咒の 提交于 2019-12-09 16:26:04

问题


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?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/17657518/boost-pointer-container-made-obsolete-by-stdunique-ptr-in-c11-14

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!