0

Take the following code

void save(){
    Classname object(aString, aInt);
    this->getVector().push_back(&object);
}

I'm trying to save to this class's vector a copy of object, but i know for a fact that this doesn't work because object is going to be deleted once i leave save(), so my question is how do i work around this? i would appreciate some code example because i'm migrating from java and might not understand some of this pointer wizardry.

edit:english edit2:copy paste never works!

MikeNeto
  • 3
  • 2
  • Use smart pointers. They maintain a reference count and automatically deallocate their memory when the last reference is released. – user229044 Dec 08 '13 at 02:12
  • 2
    Also, you could just make your vector a `vector` rather than `vector`. – Joe Z Dec 08 '13 at 02:14
  • @Joe Z but that doesn't conflict with Polymorphism? – MikeNeto Dec 08 '13 at 02:18
  • You probably want to post the return type of getVector(). If it is a copy of the vector, you probably have two bugs. Also &l is not in scope, might want to fix that to &object – rileymat Dec 08 '13 at 02:18
  • @MikeNeto: Yes, if you need it to be polymorphic, then you do need to use pointers. You can use a vector of smart pointers, as meagar suggested above. – Joe Z Dec 08 '13 at 02:20
  • @meagar could you provide me a link to some documentation, examples or videos on smart pointers? – MikeNeto Dec 08 '13 at 02:34
  • @MikeNeto http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one – user229044 Dec 08 '13 at 03:10
  • Is the vector a vector of *objects* (`vector`) or a vector of *pointers to objects* (`vector`)? – Beta Dec 08 '13 at 03:11
  • @Beta vector is a vector of pointers to objects, because i need it to use Polymorphism. – MikeNeto Dec 08 '13 at 09:55

1 Answers1

1

First, there's no need for this->, you can just say

getVector().push_back(...);

Second, since you used this->, I infer that save and getVector are two member functions of the same class; if all getVector does is give access to a vector that is also a member of the class (without any tricks like lazy instantiation), then you don't need it either, you can deal with the vector directly:

theVector.push_back(...)

Now to your question. You're right, object will pass out of scope-- if it is on the stack. But you can construct it dynamically, on the heap, and it will live until deleted:

void save(){
    Classname *ptr = new Classname(aString, aInt);
    theVector.push_back(ptr);
}

Now ptr will pass out of scope, but the copy of ptr that was added to the vector will not, and that pointer will still point to the object.

Since you want to use polymorphism, I suppose you want the vector to contain base-class pointers which can actually point to objects of derived classes. No problem:

void save(){
    Animal *ptr = new Aardvark(aString, aInt);
    theVector.push_back(ptr);   // <-- the vector is of type vector<Animal*>
}
Beta
  • 96,650
  • 16
  • 149
  • 150