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)
cHao
  • 84,970
  • 20
  • 145
  • 172
Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • 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 ? – Alexandre C. Dec 25 '10 at 21:28
  • @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. – Billy ONeal Dec 25 '10 at 21:29
  • 2
    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. – Alexandre C. Dec 25 '10 at 21:32
  • Have you tried using a vector of shared pointers? Was it really that expensive? – Fred Foo Dec 25 '10 at 21:38
  • @Iarsmans: 1. Did you read the question? 2. I'm less concerned about the computational cost as I am concerned about the ownership violation. – Billy ONeal Dec 25 '10 at 23:09

1 Answers1

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.

Puppy
  • 144,682
  • 38
  • 256
  • 465
  • 2
    I.e. implement your own `std::vector` which has the required semantics? – Billy ONeal Dec 25 '10 at 21:09
  • @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. – Puppy Dec 25 '10 at 22:15