简体   繁体   中英

please solve this memory leak problem in c++

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM