实例化时带有new关键字的C ++指针和引用 [英] C++ pointer and reference with new keyword when instantiating

查看:124
本文介绍了实例化时带有new关键字的C ++指针和引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想在C ++中实例化一个类时,我通常采用这种方式

When I want to instantiate a class in C++ I usually go this way

Book bk = new Book();

我的教授最近做了这个

Book &bk = *new Book();

他只是告诉我,他将使用引用来使用点(例如bk.getTitle();)运算符而不是箭头(例如bk-> getTitle();).我了解代码的这一部分,但是当您将*运算符与new结合使用时会发生什么?

He only told me that he would use a reference to be able to use the dot (eg bk.getTitle();) operator instead of arrow (eg bk->getTitle();). I understand this part of the code but what happens when you use the * operator in combination with new?

预先感谢

完整的示例代码位于此处,它是主函数中的数组堆栈

the full example code can be found here it is the arraystack in the main function

推荐答案

此:

Book &bk = *new Book();

与此大致相同:

Book *p = new Book();  // Pointer to new book
Book &bk = *p;  // Reference to that book

但是有一个关键的区别.在原始代码中,您没有指针,当使用完它后,就可以使用它来delete动态分配的对象,因此,您实际上已经造成了内存泄漏.

But there's one crucial difference; in the original code, you don't have a pointer which you can use to delete the dynamically-allocated object when you're done with it, so you've effectively created a memory leak.

当然,您可以这样做:

delete &bk;

但这是极端的非惯用C ++,很可能在以后引起问题.

but that's extremely non-idiomatic C++, and very likely to cause problems later.

总而言之,绝对没有充分的理由编写这样的代码,因此不要这样做.下列任何一种都可以:

In summary, there's absolutely no good reason to write code like this, so don't do it. Either of the following is fine:

Book bk;
Book bk = Book();

这篇关于实例化时带有new关键字的C ++指针和引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆