Click here to Skip to main content
15,893,814 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
If i do the following:

C++
void addObject(myObject o, const int& i) {
    o.setI(i);

    this->myVector.push_back(&o);
}


I guess o gets destroyed at the end of the function.

Thus how, can I safely keep a pointer to it in myVector?
Note that, there's no arguing about myVector storing pointers and not objects.
Posted

1 solution

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:
C++
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:
C++
void addObject(const myObject& o, const int& i) {
   myObject* po = new myObject(o); // call copy constructor
   po->set(i);
   this->myVector.push_back(po);
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 26-May-14 11:43am    
All correct, a 5.
—SA
[no name] 26-May-14 11:56am    
Nicely explained.
Andreas Gieriet 26-May-14 16:15pm    
My 5!
Cheers
Andi

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900