class A
{
public:
unique_ptr<int> m_pM;
A() { m_pM = make_unique<int>(5); };
~A() { };
public:
void loop() { while (1) {}; } // it means just activating some works. for simplifying
};
int main()
{
_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
A a;
a.loop(); // if i use force quit while activating this function, it causes memory leak
}
is there any way to avoid memory leak when i use force quit while activating this program?
CodePudding user response:
a.loop()
is an infinite loop so everything after that is unreachable, so the compiler is within its right to remove all code after the call to a.loop()
. See the compiler explorer for proof.
CodePudding user response:
I believe that outside of some niche and very rare scenarios truly infinite loops like the one you wrote here are pretty useless, since they literally mean “loop indefinitely”. So what’s the compiler supposed to do? In some sense it just postpones the destruction of your object until some infinite time in the future.
What you usually do is use break
inside such loop and break when some condition is met. A simplified example: https://godbolt.org/z/sxr7eG4W1
Here you can see the unique_ptr::default_delete in the disassembly and also see that the compiler is actually checking the condition inside the loop.
Note: extern volatile is used to ensure the compiler doesn’t optimise away the flag, since it’s a simplified example and the compiler is smart enough to figure out that the flag is not changed. In real code I’d advice against using volatile. Just check for the stop condition. That’s it.