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:
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)auto_ptr is a class template that was available in previous versions of the C++ standard library (declared in the <memory> header file), which provides some basic RAII features for C++ raw pointers. It has been replaced by the unique_ptr class.
Since the assignment-semantics was most-disliked feature, they wanted that feature to go away, but since there is code written that uses that semantics, (which standards-committee can not change), they had to let go of auto_ptr, instead of modifying it.
Why is auto_ptr deprecated? It takes ownership of the pointer in a way that no two pointers should contain the same object. Assignment transfers ownership and resets the rvalue auto pointer to a null pointer. Thus, they can't be used within STL containers due to the aforementioned inability to be copied.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With