Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 824
Billy ONeal Avatar asked Dec 25 '10 20:12

Billy ONeal


People also ask

What replaces auto_ptr?

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.

Why was auto_ptr removed?

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?

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.


1 Answers

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.

like image 148
Puppy Avatar answered Oct 17 '22 18:10

Puppy