(c++)在语句结束后,在if语句中创建的堆对象会发生什么?
正如标题所暗示的那样,我想知道在调用关闭括号后,我在语句/循环/任何其他功能中创建的堆对象的可用性。作为一个简约的例子:
class Foo
{
private:
int Bar;
public:
Foo(int bar) : Bar(bar) {}
int GetBar()
{
return Bar;
}
};
int main()
{
if (true)
{
Foo* foo = new Foo(6);
}
foo.GetBar();
}
在这种情况下,我希望我在IF语句范围内创建的FOO实例在闭幕式后生存,因为我用“ New”在堆上创建了它。但是,我无法使用结束括号后无法访问它,而foo.getbar()无法使用。我已经证实,当我使用“新”时,在IF语句的结束括号中没有调用destructor(而不是何时在堆栈上实例化),但是我再也无法获得参考。这是否意味着我只是失去对对象的引用,但仍在内存中,导致内存泄漏?关闭括号后有没有办法保留参考?
事先感谢您的帮助。
as the title suggests I was wondering about the availability of the heap objects I create inside if statements/for loops/any other functions, after the closing bracket is called. As a minimalistic example:
class Foo
{
private:
int Bar;
public:
Foo(int bar) : Bar(bar) {}
int GetBar()
{
return Bar;
}
};
int main()
{
if (true)
{
Foo* foo = new Foo(6);
}
foo.GetBar();
}
In this case, I'd expect the instance of foo I've created inside the scope of the if statement to survive after the closing bracket, since I created it on the heap with "new". However, I cannot access it after the closing brackets and foo.GetBar() can't be used. I've verified that when I use "new", no destructor is called on the closing bracket of the if statement (as opposed to when I just instantiate it on the stack), but I cannot get the reference anymore. Does that mean that I am simply losing reference to the object but it is still in the memory, causing a memory leak ? Is there a way to hold on to the reference after the closing brackets ?
Thanks in advance for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
除非您手动使用
delete
,否则新的
的内存将不会删除。但是指针foo
将在时删除。为了避免内存泄漏,您需要始终使用该指针。例如,您可以
感谢Fabian,他注意到FOO是一个需要
- >
而不是。
的指针。The memory from
new
will not be deleted unless you manually usedelete
. But the pointerfoo
will be deleted afterif
.To avoid memory leak, you need to always have that pointer. For example, you can
Thanks to fabian, who noticed that foo is a pointer that need
->
rather than.
.