Boost.Pointer容器在C++11/14中被std::unique_ptr废弃

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

本文关键字:std unique 废弃 ptr 中被 Pointer C++11 Boost      更新时间:2023-10-16

std::unique_ptr是否使Boost.Pointer Container库在C++11/14中过时?

在C++98/03中,没有移动语义,并且与原始指针相比,像shared_ptr这样的智能指针具有与引用计数相关的开销(对于引用计数块和互锁的增量/递减)。因此,与std::vector<T*>相比,像std::vector<shared_ptr<T>>这样的东西有开销。

但是,在异常和自动销毁方面,std::vector<std::unqiue_ptr<T>>是否与std::vector<T*>(无引用计数开销)、一样高效,以及安全(即vector<unique_ptr<T>>析构函数将自动调用指针存储在vector中的T项的析构函数)?

如果是这样的话,Boost.Pointer容器在C++11/14代码中是否仍然有一个有效的有用位置,或者它只是过时了?

它不是obdelete;它有一个完全不同的比CCD_ 10更直观的界面。

James在回答中提到,与将unique_ptr插入标准库容器相比,Boost.Pointer容器提供了更直观的界面。

除此之外,boost::ptr_vector<T>(和朋友)将指向的类型存储为下面的void *,因此不会为每个T获得整个类模板实例化。vector<unique_ptr<T>>的情况并非如此。

尝试使用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

指针容器当然有更直观的界面。