What's the best way to return something like a collection of `std::auto_ptr`s in C++03?

℡╲_俬逩灬. 提交于 2019-12-22 04:48:13

问题


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 in void *s which means it's difficult to view the object actually stored inside the container in the debugger)

回答1:


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.



来源:https://stackoverflow.com/questions/4531643/whats-the-best-way-to-return-something-like-a-collection-of-stdauto-ptrs-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!