Using this definition,
o
is a temporary variable holding a copy of the object passed to the function, and that temporary will indeed be destroyed upon leaving the function.
There are two possible solutions, depending on what you want:
1. If you're ok to just keep a reference to an existing object, all you need to do is pass the object by reference, rather than by value:
void addObject(myObject& o, const int& i) {
In this case,
o
is a reference, and
&o
is a pointer to the object passed to the function.
2. If you want a copy of the original object that survives the scope of the function, you need to create the copy on the heap, rather than the stack. Note that in this case you also should pass the original object by reference - just make it a
const
reference this time:
void addObject(const myObject& o, const int& i) {
myObject* po = new myObject(o); po->set(i);
this->myVector.push_back(po);
}