Vector of pointers to classes

I'm not very used to program in C++ , but I'm working in a robotics project using the Player/Stage environment, wich has a C++ library included.In this library I have some classes wich correspond to the robots and the information about them namely the PlayerClient and Position2dProxy classes.
As I'm working with multiple robots I have to be able to create a vector of these clients, so I can access each one by an index.
The problem is, when I try to create a vector of pointers to these classes(it has to be, because the objects themselves can't be copied) , I get some bugs in my program wich I assume to be related to bad memory management. Researching on the net I found out about smart pointers(speciffically the auto_ptr), wich is a wrapper class to common pointers that manage the memory automatically(i.e set the pointers to null when the objects they point to are destroyed ,etc).
Now I'm having problems declaring these vectors.This is what I tried:
1
2
vector < auto_ptr<PlayerClient> > clients ;
clients.push_back( new PlayerClient(args) ) ;

But that generates a compile error on the second line saying "no matching function to call".What's the correct way to create these objects?

Thank you in advance,
Luiz.
Last edited on
Never put auto_ptrs in STL containers. Consider Boost.SmartPtr (probably boost::shared_ptr) or Boost.PointerContainer. A quick Google search will give you more information, if necessary.

http://www.boost.org/
Last edited on
Ok, I'll look for it.But I suppose it's use is similar to that of auto_ptr.How would I insert new objects in the vector above correctly?(supposing it's not auto_ptr anymore but shared_ptr).
If you use boost pointer containers (which I highly suggest), yes, you just push new'd stuff into them.
There are examples in the Boost documentation for either.

Shared pointers are reference counted to provide a kind of garbage collection facility. Is exception safety a requirement for your application? You may be just fine storing regular pointers and doing the cleanup yourself.
I always thought this was strange....

if auto_ptr transfers ownership, why can't you put it in a std container? That makes no sense to me.
There's no reason to use a vector of shared pointers in this case, ptr_vector is the way to go.


if auto_ptr transfers ownership, why can't you put it in a std container? That makes no sense to me.

See http://www.gotw.ca/publications/using_auto_ptr_effectively.htm under "Things Not To Do, and Why Not To Do Them".
Last edited on
It's this kind of non-orthogonal craziness that makes me hate C++... ...it's like you have to know all the implementation details of auto_ptr and stl in order to avoid stepping in doo doo.

http://www.devx.com/tips/Tip/13606

Note the last line in the article - there are, apparently, other smart pointers that are fine inside stl.
Topic archived. No new replies allowed.