C++ 中变量声明的差异
Class A
{
};
A a
、 A* a
和 A* a = new A()
之间有什么区别。
Class A
{
};
What is the difference between A a
, A* a
and A* a = new A()
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用默认构造函数创建位于堆栈中的 A 实例。
只是一个指向 A 的未初始化指针。此时它实际上并不指向 A 对象,但可以。已初始化的指针(在本例中设置为 NULL)如下所示:
此处的区别在于,空指针不指向任何对象,而未初始化的指针可能指向任何地方。初始化指针是一个很好的做法,以免您发现自己想知道为什么程序会崩溃或产生不正确的结果。
同样,您不想尝试取消引用 NULL 指针或未初始化的指针。但你可以测试 NULL 指针。测试未初始化的指针会产生不确定的错误结果。它实际上可能是 != 0 但肯定不会指向您想要它指向的任何地方。确保在测试指针之前初始化指针,并在尝试取消引用指针之前测试指针。
应该写成
并创建一个在堆上分配的新 A 对象。 A 对象是使用默认构造函数创建的。
如果没有为类显式编写默认构造函数,则编译器将隐式创建一个默认构造函数,尽管我不相信该标准没有指定隐式实例化对象的数据成员的状态。有关隐式默认构造函数的讨论,请参阅 Martin York 对这个 SO 问题的回复。
Creates an instance of an A that lives on the stack using the default constructor.
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:
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.
should be written as
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
声明一个名为a
的A
实例A *a
声明一个指向A< /code> class
A *a = new A()
在堆上为a
分配空间并调用正确的构造函数(如果没有指定构造函数,则执行默认初始化) 。有关最后一个表单的更多信息,请参阅 http://en.wikipedia。 org/wiki/New_%28C%2B%2B%29
A a
declares an instance ofA
nameda
A *a
declares a pointer to aA
classA *a = new A()
allocates space fora
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