开发者

Differences in variable declarations in C++

Class A 
{
};

开发者_Go百科What is the difference between A a , A* a and A* a = new A().


A a;

Creates an instance of an A that lives on the stack using the default constructor.

A *a;

Is simply a uninitialized pointer to an A. It doesn't actually point to an A object at this point, but could. An initialized pointer (in this case, set to NULL) would look like so:

A *a = 0;

The difference here is that a null pointer does not point to any object while an uninitialized pointer might point anywhere. Initializing your pointers is a good practice to get into lest you find yourself wondering why your program is blowing up or yielding incorrect results.

Similarly, you don't want to attempt to dereference either a NULL pointer or an uninitialized pointer. But you can test the NULL pointer. Testing an uninitialized pointer yields undetermined and erroneous results. It may in fact be != 0 but certainly doesn't point anywhere you intend it to point. Make sure you initialize your pointers before testing them and test them before you attempt to dereference them.

A a = new A();

should be written as

A *a = new A();

and that creates a new A object that was allocated on the heap. The A object was created using the default constructor.

Where a default constructor is not explicitly written for a class, the compiler will implicitly create one though I don't believe the standard does not specify the state of data members for the object implicitly instantiated. For a discussion about implicit default constructors, see Martin York's response to this SO question.


A a declares an instance of A named a

A *a declares a pointer to a A class

A *a = new A() allocates space for a on the heap and calls the proper constructor (if no constructor is specified, it performs default initialization).

For further information about the last form see http://en.wikipedia.org/wiki/New_%28C%2B%2B%29

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜