C ++在堆栈中分配类,而不是在堆中

时间:2015-09-17 22:14:30

标签: c++

我的问题是,下面的声明是在堆栈上还是在堆上分配?

List * aList = new List();

目标是有一个指向堆栈中对象的指针。

1 个答案:

答案 0 :(得分:5)

它从堆中分配。 要获得指向堆栈内存的指针,请执行

{
  List aList;
  List* pointer = &aList;
  // use aList or pointer here
  pointer->push(foo);
} // aList is destroyed here

警告,不要保存指针供以后使用,因为当花括号结束当前块时,aList会被销毁。

例如不要这样做

List* pointer;
{
  List aList;
  pointer = &aList;;
} // aList is destroyed here

pointer->push(foo);  // oh uh, if you are lucky you get a crash; if not your
                     // data is corrupted 
相关问题