带有 std::unique_ptr 的 stl 容器 vs boost::ptr_container

stl container with std::unique_ptr#39;s vs boost::ptr_container(带有 std::unique_ptr 的 stl 容器 vs boost::ptr_container)

本文介绍了带有 std::unique_ptr 的 stl 容器 vs boost::ptr_container的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有了 c++11,我在问自己是否可以替代 c++11 中的 boost::ptr_containers.我知道我可以使用例如一个 std::vector;>,但我不确定这是否是一个完整的替代品.处理这些情况的推荐方式是什么?

With c++11 out there, I was asking myself if there is a replacement of the boost::ptr_containers in c++11. I know I can use e.g. a std::vector<std::unique_ptr<T> >, but I'm not sure if this is a complete replacement. What is the recommended way of handling these cases?

推荐答案

他们确实解决了两个相似但不同的问题.

They really solve two similar but different problems.

指针容器是一种将对象存储在容器中的方法,这些对象恰好是指向已分配内存而不是值的指针.他们尽其所能隐藏一个事实,即他们是一个指针容器.这意味着:

A pointer container is a way to store objects in a container that just so happen to be pointers to allocated memory rather than values. They do everything in their power to hide the fact that they are a container of pointers. This means:

  • 容器中的条目不能为 NULL.
  • 您从迭代器和函数中获得的值是对类型的引用,而不是类型的指针.
  • 使用许多标准算法可能......很棘手.而棘手",我的意思是破碎.指针容器有自己的内置算法.

然而,事实上,指针容器知道它们是指针的容器,它们可以提供一些新的功能:

However, the fact that pointer containers know that they're containers of pointers, they can offer some new functionality:

  • 一个 clone 成员函数,它通过在对象类型上使用某个可克隆"概念来执行深度复制.
  • 容器释放其对象所有权的能力(例如,在浅拷贝之后).
  • 内置函数可将所有权转让给其他容器.
  • A clone member function that performs a deep copy, via the use of a certain "Cloneable" concept on the type of the object.
  • The ability of a container to release ownership of its objects (after a shallow copy, for example).
  • Built-in functions to transfer ownership to other containers.

它们确实是完全不同的概念.有很多事情你必须手动完成,而指针容器可以使用专门的函数自动完成.

They really are quite different concepts. There is a lot of stuff you would have to do manually that pointer containers can do automatically with specialized functions.

如果你真的需要一个指针的容器,那么你可以使用unique_ptr的容器.但是,如果您需要存储一堆碰巧在堆上分配的对象,并且您想与它们玩涉及所有权等的特殊游戏,那么指针容器不是一个坏主意.

If you really need a container of pointers, then you can use containers of unique_ptr. But if you need to store a bunch of objects that you happen to heap allocate, and you want to play special games with them involving ownership and such, then the pointer containers are not a bad idea.

这篇关于带有 std::unique_ptr 的 stl 容器 vs boost::ptr_container的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:带有 std::unique_ptr 的 stl 容器 vs boost::ptr_container

基础教程推荐