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

1

7

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)
Horrific answered 25/12, 2010 at 20:51 Comment(5)
Did you consider using a class which holds a std::vector of pointers as a public member, and implement only constructors, destructor, copy, swap and assignment ?Minta
@Alexandre C.: I haven't considered much of anything at this point -- it's such a common and general problem that I want to see how others have solved it before I try to do it myself.Horrific
not so common in fact. When using a container of polymorphic objects, I use boost::ptr_vector if I need the full vector interface, or what I mentioned (although with a private member) when I only use the collection internally.Minta
Have you tried using a vector of shared pointers? Was it really that expensive?Commonable
@Iarsmans: 1. Did you read the question? 2. I'm less concerned about the computational cost as I am concerned about the ownership violation.Horrific
C
3

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.

Catfall answered 25/12, 2010 at 20:58 Comment(2)
I.e. implement your own std::vector which has the required semantics?Horrific
@Billy: Yes. Of course, if you know the exact context in which the own::vector will be used, then you can implement the absolute bare minimum for it to survive in such a context.Catfall

© 2022 - 2024 — McMap. All rights reserved.