(c++)在语句结束后,在if语句中创建的堆对象会发生什么?

发布于 2025-02-11 02:13:04 字数 537 浏览 2 评论 0原文

正如标题所暗示的那样,我想知道在调用关闭括号后,我在语句/循环/任何其他功能中创建的堆对象的可用性。作为一个简约的例子:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一向肩并 2025-02-18 02:13:04

除非您手动使用delete,否则新的的内存将不会删除。但是指针foo将在时删除。
为了避免内存泄漏,您需要始终使用该指针。例如,您可以

int main()
{
    Foo* foo;
    if (true)
    {
        foo = new Foo(6);
    }
    foo->GetBar();
}

感谢Fabian,他注意到FOO是一个需要- >而不是的指针。

The memory from new will not be deleted unless you manually use delete. But the pointer foo will be deleted after if.
To avoid memory leak, you need to always have that pointer. For example, you can

int main()
{
    Foo* foo;
    if (true)
    {
        foo = new Foo(6);
    }
    foo->GetBar();
}

Thanks to fabian, who noticed that foo is a pointer that need -> rather than ..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文