views:

126

answers:

2

It may be a bit confusing, but...

Let's say I have a vector type member in a class, something like vector<Operator*> ( I have methods on my class to return Operators from this container). Now lets say that I have a method on my class that receives an Operator object op and inserts it on the vector. What I want to know is: will I have any trouble by insert it directly into the vector (push_back(&op))? Or should I use the copy constructor to create a new Operator and then put this new one on the vector (with push_back(new Operator(op)))?

(Operator is a class I created)

+2  A: 

Using &op only gives you a pointer to the object (which is still on the stack) and not a copy. Thus when the object goes out of scope (and gets cleaned up) the pointer in the vector becomes invalid and will cause issues.

Your best bet is to use the copy constructor as you suggested above.

Lodle
What Lodle said: if you just push the address, there's no guarantee that when you go to dereference it later it'll be there. If you've created your object with 'new', it'll persist until you 'delete' it; if you've created it automatically (i.e., with an automatic declaration), it might not persist. If it's globally defined, you'll probably be ok (i.e., you wont have to copy it).
Rooke
A: 

OK, let me see if I follow what you are trying to do. You've got a class you've created called Operator. You've got a vector <Operator *> and you're wondering if there will be issues with this.

Short answer is yes, there could be. It is about the scope of the vector because when it goes out of scope, the memory allocated on the heap for all those Operator objects that you've got pointers to in the vector will NOT be cleaned up by the vector. In an unmanaged language like c++, unless you are using a specialized class that takes care of things for you, you've got to be keenly aware of scoping and potential memory leaks.

Two questions you need to ask yourself are "Who owns the Operator objects?" and "Who is responsible for cleaning up the Operator objects that were allocated on the heap and are pointed to by the pointers in the vector?"

You can clean that memory up yourself when the destructor is called for the object that owns the vector.

I think you might want to look at this SO question that is similar. There are other solutions - using boost classes, for instance, that might be better.

itsmatt