为什么我需要调用new? [英] Why do I need to call new?

查看:133
本文介绍了为什么我需要调用new?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能的重复项:

何时使用新建按钮?而不是在C ++中?

何时在C ++中使用新关键字?

似乎我可以编程的东西,而不使用单词 new ,我永远不必担心删除任何东西,为什么我应该调用它?

It seems like I could program something without ever using the word new, and I would never have to worry about deleting anything either, so why should I ever call it?

从我的理解,这是因为我会用尽堆栈内存。

From what I understand, it's because I would run out of stack memory.

这是正确的吗?我想我的主要问题是,我应该什么时候调用 new

Is this correct? I guess my main question is, when should I call new?

推荐答案

这是一个对象生命周期问题:如果你堆栈分配你的对象,当这些对象超出范围时,对象析构函数将被调用(例如,在方法的结尾)。这意味着,如果你把这些对象从创建它们的方法,你会发现自己指向内存的指针,可以随时覆盖。

It's a matter of object lifetime: if you stack-allocate your objects, the objects destructors will be called when these objects go out of scope (say, at the end of the method). This means that if you pass these objects out of the method that created them, you'll find yourself with pointers to memory that could be overwritten at any time.

这篇关于为什么我需要调用new?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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