What does the 'new' keyword do in c++?

Possible Duplicates:
When to use “new” and when not to, in C++?
When should I use the new keyword in C++?

What is the difference between A a; and A a = new A(); ?

Edited :

A* a = new A();

My mistake.


When inside a function,

A a

declares a variable on the stack and calls A's default constructor* on a. This variable is automatically cleaned up when the variable goes out of scope.

A a = new A(); 

won't compile, however

A* a = new A(); 

creates a new A on the heap and calls A's default constructor* on the newly allocated memory. Then the expression in turn evaluates to a pointer to the new A, which the variable a is initialized to . You're in charge of managing this memory, so you need to be sure to later delete it with delete:

delete a;

or else you'll have a memory leak

See this question to learn more about the differences between the stack and the heap.

* None of this code will compile if A doesn't have a default constructor. A default constructor is either defined by you or implicitly provided by the compiler. See here for more on default constructors.


Doug T :

A a declares a variable on the stack.

Incorrect : A a declares a variable and allocated the memory for it, either on the stack or in global memory space depending on what scope it has.

Consider also where in memory

static A a

is located (Global memory space - not stack, not heap).


The second is invalid. new allocates space and returns a pointer. Use A* a = new A();

链接地址: http://www.djcxy.com/p/96528.html

上一篇: 我应该何时使用“新”?

下一篇: 'new'关键字在c ++中做了什么?