stl容器与std :: unique_ptr的对boost :: ptr_container [英] stl container with std::unique_ptr's vs boost::ptr_container

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

问题描述

有了c ++ 11,我问自己,如果有一个替换boost :: ptr_containers在c ++ 11。我知道我可以使用a std :: vector< std :: unique_ptr< T> > ,但我不知道这是否是一个完全替代。

解决方案

它们真正解决了两个相似但不同的问题。



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




  • 容器中的条目不能为空。

  • 您从迭代器和

  • 使用许多标准算法可能会很麻烦。而棘手,我的意思是破碎。指针容器有自己内置的算法。



但是,指针容器知道它们可以提供一些新的功能:




  • A clone

  • 容器释放其对象的所有权的能力(在一个对象的所有者之后)




他们真的是完全不同的概念。有很多的东西,你必须手动做的指针容器可以自动用专门的函数。



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


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:

  • Entries in the container cannot be NULL.
  • Values you get from iterators and functions are references to the type, not pointers to the type.
  • Working with many standard algorithms can be... tricky. And by "tricky", I mean broken. Pointer containers have their own built-in algorithms.

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

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

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.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆