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.