I have a std::list<obj*>, where obj is my class:
std::list<obj*> list_of_ptr;
list_of_ptr.push_back(new obj());
I want to convert this list to the equivalent std::list<obj>, after that I no longer need the list_of_ptr.
What is the fastest way to do this work?
std::transformis your friend:Or, if C++11 lambda expressions cannot be used, one may use a simple function object to perform the indirection:
Or, using
boost::indirect_iterator:These, of course, assume that there are no null pointers in the sequence. It is left as an exercise for the reader to figure out how to correctly manage the lifetimes of the objects pointed to by the pointers in
list_of_ptr.Ideally, one would use a
std::vector<obj>from the start, or, if that is not possible, a container of smart pointers. Manually managing the lifetimes of the pointed-to objects, and doing so correctly, is very difficult. C++ has awesome automatic object lifetime management facilities (destructors, smart pointers, containers, stack semantics, RAII), and there is no reason not to use them.