Reputation: 3927
have this code:
void set(list<Person*>* listP){
Person timmy = Person(10);
listP->push_back(&timmy);
}
int main()
{
list<Person*> listP;
set(&listP);
Person* timmy = listP.back();
}
If i understand correct (please correct me) timmy is allocated on the stack , so i cannot count on the values of timmy when i use them in the main. Am i correct? do i need to create timmy like this:
Person* timmy = new Person(10);
in order to create it on the heap and not on the stack ,so it will not be destroyed after method return?
Thank you
Upvotes: 3
Views: 163
Reputation: 227588
Your assumption is correct, but you don't have to create timmy
on the "heap", if you use a list
of Person
s instead:
void set(list<Person>& listP){
listP.push_back(Person(10));
}
It is extremely likely that no extra person copies will be made in the . In C++11, even if the copy wasn't elided, move semantics could kick in and expensive copying.push_back
(copy elision)
Upvotes: 2
Reputation: 24866
void set(list<Person*>* listP){
Person timmy = Person(10); // create timmy on automatic storage (stack)
listP->push_back(&timmy); //push timmy's address
} //timmy is destroyed. pushed address points to deallocated memory
Yes, you need to use Person* timmy = new Person(10);
to allocate on heap.
void set(list<Person*>* listP){
Person *timmy = new Person(10); // timmy is a pointer now
listP->push_back(timmy); //push timmy's copy (copy of pointer)
} //timmy (pointer) is destroyed, but not the memory it points to
Also prefere to use smart_pointers
such as std::shared_ptr
, std::unique_ptr
or boost
smart pointers. It will simplify memory management and writing exception-safe
code
Upvotes: 2