Hugo Riggs
Hugo Riggs

Reputation: 79

C++ allocating class in stack, not in heap

My question is, does the declaration below allocate on the stack, or on the heap?

List * aList = new List();

The objective is to have a pointer that points to an object in the stack.

Upvotes: 1

Views: 118

Answers (1)

Mark Lakata
Mark Lakata

Reputation: 20838

It allocates from the heap. To get a pointer that points to stack memory, do

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

Warning, don't save the pointer for later use, as aList is destroyed when the curly braces end the current block.

For example DO NOT DO THIS

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 

Upvotes: 5

Related Questions