使用Exit()函数时,有什么方法可以防止内存泄漏?
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
}
假设只有与宏检测到的内存泄漏。 我认为,如果我在循环中使用exit(),则无法防止内存泄漏。 因为exit()未调用destructor so Uniquar_ptr无法释放他的分配记忆。
我正确吗?还是在使用Exit()时是否有其他方法可以调用驱动器?
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
}
Assuming only memory leaks detected by VS macros.
i think there are no way to prevent memory leak if i use exit() in the loop.
because exit() doesnt call destructor so unique_ptr cant free his allocated memory.
Am I correct? or is there some other way to call destructor when use exit()?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
a.loop()
是一个无限的循环,因此之后的所有内容都无法到达,因此编译器在访问a.loop()
之后删除所有代码的权利之内。请参阅 Compiler Explorer 以获取证明。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 toa.loop()
. See the compiler explorer for proof.我相信,除了您在这里写的那样,除了一些利基市场和非常罕见的场景之外,它确实是毫无用处的,因为它们实际上是“无限期的循环”。那么编译器该怎么办?从某种意义上说,它只是推迟对象的破坏,直到将来的某个无限时间。
您通常要做的是在循环中使用
Break
在满足某些条件时休息。一个简化的示例: https://godbolt.org/z/sxr7eg4w1在这里,您可以在拆卸中看到unique_ptr :: default_delete,还可以看到编译器实际上正在检查循环内的条件。
注意:外部挥发性用于确保编译器不会优化标志,因为这是一个简化的示例,并且编译器足够聪明,可以弄清楚标志没有更改。在实际代码中,我建议不要使用挥发性。只需检查停止条件即可。就是这样。
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/sxr7eG4W1Here 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.