我们都知道RAW指针需要包装在某种形式的智能指针中才能获得异常安全的内存管理。 但当涉及到指针容器时,问题就变得更加棘手。
std 容器坚持要求所包含的对象是可复制的,因此这排除了 std::auto_ptr 的使用,尽管您仍然可以使用 boost::shared_ptr 等。
但也有一些明确设计用于安全保存指针的 boost 容器:
请参阅指针容器库
问题是:
在什么情况下我应该更喜欢使用 ptr_containers 而不是 smart_pointers 容器?
boost::ptr_vector<X>
or
std::vector<boost::shared_ptr<X> >
We all know that RAW pointers need to be wrapped in some form of smart pointer to get Exception safe memory management. But when it comes to containers of pointers the issue becomes more thorny.
The std containers insist on the contained object being copyable so this rules out the use of std::auto_ptr, though you can still use boost::shared_ptr etc.
But there are also some boost containers designed explicitly to hold pointers safely:
See Pointer Container Library
The question is:
Under what conditions should I prefer to use the ptr_containers over a container of smart_pointers?
boost::ptr_vector<X>
or
std::vector<boost::shared_ptr<X> >
发布评论
评论(3)
稳定:智能指针是处理资源管理的一种非常好的方法,但不是唯一的方法。 我同意您在编写良好的 C++ 代码中会看到很少的原始指针,但根据我的经验,您也不会看到很多智能指针。 有许多使用原始指针容器实现的完全异常安全的类。
Steady on: smart pointers are a very good method of handling resource management, but not the only one. I agree you will see very few raw pointers in well-written C++ code, but in my experience you don't see that many smart pointers either. There are plenty of perfectly exception-safe classes implemented using containers of raw pointers.
嗯,开销是一种情况。
共享指针向量将执行大量无关的复制,其中涉及在调整大小时创建新的智能指针、递增引用、递减引用等。 所有这些都可以通过指针容器来避免。
需要进行分析以确保容器操作是瓶颈:)
Well, overhead is one case.
A vector of shared pointers will do a lot of extraneous copying that involves creating a new smart pointer, incrementing a reference, decrementing a reference, etc on a resize. All of this is avoided with a pointer container.
Requires profiling to ensure the container operations are the bottleneck though :)
Boost 指针容器对其所持有的资源具有严格的所有权。 std::vector> 拥有共同所有权。 这可能是有必要的,但如果不是,我会默认使用 boost::ptr_vector。 YMMV。
Boost pointer containers have strict ownership over the resources they hold. A std::vector<boost::shared_ptr<X>> has shared ownership. There are reasons why that may be necessary, but in case it isn't, I would default to boost::ptr_vector<X>. YMMV.