0

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.

trincot
  • 317,000
  • 35
  • 244
  • 286
  • 1
    The pointer `foo` will go out of scope but the dynamically allocated object of type `Foo` will still exist and not be destroyed automatically. Note that you can't use poniter `foo` after the `if`. Also you need to use `->` instead of `.` with `foo`. – Jason Jun 26 '22 at 14:01

1 Answers1

2

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 ..

wznmickey
  • 35
  • 6
  • 1
    The pointer will **not** be deleted; it will be destroyed, and its destructor doesn't do anything. +1. – Pete Becker Jun 26 '22 at 14:40
  • @fabian `.` works perfectly fine for member access for any type. Some, like raw pointers, don't have any members to access though. – Deduplicator Jun 26 '22 at 21:05