堆栈内存中销毁的对象

时间:2015-05-09 05:42:44

标签: c++

让我们说我有一个叫做名字,年龄

的构造函数的人
void addPerson(list<person> &list)
{
  person p("Michael", 19);
  list.push_back(p);
}

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

我知道列表的大小将是1,但我觉得p的范围只是在addPerson()方法中,一旦方法完成,p将被破坏并且内存为p hold将被释放,这意味着main中的列表将丢失此元素?

1 个答案:

答案 0 :(得分:1)

让我们逐个完成您的addPerson功能。

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

如果运行,将打印两个cout语句。 为了完整起见,我们还要看一下主要功能:

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