user4881093
user4881093

Reputation:

object destroyed in stack memory

let's say I have a class called person with constructor of name,age

void addPerson(list<person> &list)
{
  person p("Michael", 19);
  list.push_back(p);
}

int main
{
   list<person> list;
   addPerson(list);
   cout<<list.size();
}

I know the list's size is going to be 1, but I feel like as p's scope is only in addPerson() method, once the method finishes, p will be destroyed and memory that p holds will be released, which means list in main will lose this element?

Upvotes: 0

Views: 53

Answers (1)

user1978011
user1978011

Reputation: 3589

Lets go through your addPerson function one by one.

void addPerson(list<person> &list)
{
  person p("Michael", 19); // creates a person object on the stack
  list.push_back(p); // makes a copy of p and stores that; this copy will be on the heap

  // provided, you have a comparison operator
  if (p == list.back())  // you have two identical instances now
     std::cout << "same person content\n";

  if (&p != &list.back()) // look at the address in memory
     std::cout << "persons are not identical\n";
} // p goes out of scope and is destroyed, the copy in list lives on

If run, both cout statements would be printed. For completeness, let's also look at the main function:

int main
{
   list<person> list;
   addPerson(list); // call by reference, the function acts very same instance of the first line
   cout<<list.size();
}

Upvotes: 1

Related Questions