dmessf
dmessf

Reputation: 1013

C++ Pointers, objects, etc

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)

Upvotes: 0

Views: 255

Answers (2)

itsmatt
itsmatt

Reputation: 31416

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.

Upvotes: 1

Lodle
Lodle

Reputation: 32227

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.

Upvotes: 2

Related Questions