什么是最好的方式来返回类似的`std :: auto_ptr`的集合在C ++ 03? [英] What's the best way to return something like a collection of `std::auto_ptr`s in C++03?
问题描述
std :: auto_ptr
不允许存储在STL容器中,例如 std :: vector
。但是,偶尔有些情况下,我需要返回一个多态对象的集合,因此我不能返回一个对象的向量(由于切片问题)。我可以使用 std :: tr1 :: shared_ptr
并将它们粘贴在向量
中,但是我必须支付维持单独引用计数的高价格,以及拥有实际内存(对象)的对象不再逻辑上拥有对象,因为它们可以被复制出来而不考虑所有权。
C ++ 0x以 std :: vector< std :: unique_ptr< t>
的形式为此问题提供了完美的解决方案,无法访问C ++ 0x。
其他一些注意事项:
- 我没有访问C ++ 0x,但我有TR1可用。
- 我想避免使用Boost(虽然如果没有其他选项)
- 我知道
boost :: ptr_container
容器(即boost :: ptr_vector
),但我想避免这是因为它打破了调试器(内部存储在void *
s这意味着很难查看实际存储的对象
我会做的是封装一个本地堆数组。您可以定义任何可以支持的向量界面的子集,而不需要可复制性。
std::auto_ptr
is not allowed to be stored in an STL container, such as std::vector
. However, occasionally there are cases where I need to return a collection of polymorphic objects, and therefore I can't return a vector of objects (due to the slicing problem). I can use std::tr1::shared_ptr
and stick those in the vector
, but then I have to pay a high price of maintaining separate reference counts, and object that owns the actual memory (the container) no longer logically "owns" the objects because they can be copied out of it without regard to ownership.
C++0x offers a perfect solution to this problem in the form of std::vector<std::unique_ptr<t>>
, but I don't have access to C++0x.
Some other notes:
- I don't have access to C++0x, but I do have TR1 available.
- I would like to avoid use of Boost (though it is available if there is no other option)
- I am aware of
boost::ptr_container
containers (i.e.boost::ptr_vector
), but I would like to avoid this because it breaks the debugger (innards are stored invoid *
s which means it's difficult to view the object actually stored inside the container in the debugger)
What I would do is encapsulate a native heap array. You can define whatever subset of vector's interface you can support without requiring copyability.
这篇关于什么是最好的方式来返回类似的`std :: auto_ptr`的集合在C ++ 03?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!