std::exit 会泄漏内存吗?
Can std::exit leak memory?
为了回答我的问题,我进行了一些测试:
(复制以下内容是必要的)
#include <cstdlib>
#include <memory>
我创建了一个名为 std::exit
的函数,在 main
函数中有一个 std::unique_ptr
。
void some_function()
{
std::exit(EXIT_SUCCESS);
}
int main()
{
std::unique_ptr<int> relying_on_raii{new int{5}};
}
如果我在 unique_ptr
声明之后调用 some_function
,内存可能会泄漏。
我从 Dr. Memory 得到的两个日志在以下行不同:
1 potential leak(s) (suspected false positives)
[…]
6 unique, 6 total, 797 byte(s) of still-reachable allocation(s)
对比
1 potential leak(s) (suspected false positives)
[…]
7 unique, 7 total, 801 byte(s) of still-reachable allocation(s)
可以看出,在第二个示例中,发生了第 7 次潜在泄漏,大小为 4 个字节,正好是 int
的大小。当我用 double 重复这个测试时,在 std::exit
.
的测试中确实是 805 byte(s)
那么 std::exit
是一个可以安全使用的函数吗,或者您是否应该始终从 main return 以防止内存泄漏?
So is std::exit a safe function to use, or should you always return from main to prevent memory leaks?
是的,它会泄漏内存。
不过,这是不太令人担忧的问题。更重要的问题是,如果您的程序获取了无法通过关闭进程释放的资源。要处理这种情况,最好是 return 带有一些错误状态,直到您能够退出 main
或使用 try-throw-catch
以确保 main
能够捕获所有未捕获的异常并优雅地退出。
为了回答我的问题,我进行了一些测试:
(复制以下内容是必要的)
#include <cstdlib>
#include <memory>
我创建了一个名为 std::exit
的函数,在 main
函数中有一个 std::unique_ptr
。
void some_function()
{
std::exit(EXIT_SUCCESS);
}
int main()
{
std::unique_ptr<int> relying_on_raii{new int{5}};
}
如果我在 unique_ptr
声明之后调用 some_function
,内存可能会泄漏。
我从 Dr. Memory 得到的两个日志在以下行不同:
1 potential leak(s) (suspected false positives)
[…]
6 unique, 6 total, 797 byte(s) of still-reachable allocation(s)
对比
1 potential leak(s) (suspected false positives)
[…]
7 unique, 7 total, 801 byte(s) of still-reachable allocation(s)
可以看出,在第二个示例中,发生了第 7 次潜在泄漏,大小为 4 个字节,正好是 int
的大小。当我用 double 重复这个测试时,在 std::exit
.
805 byte(s)
那么 std::exit
是一个可以安全使用的函数吗,或者您是否应该始终从 main return 以防止内存泄漏?
So is std::exit a safe function to use, or should you always return from main to prevent memory leaks?
是的,它会泄漏内存。
不过,这是不太令人担忧的问题。更重要的问题是,如果您的程序获取了无法通过关闭进程释放的资源。要处理这种情况,最好是 return 带有一些错误状态,直到您能够退出 main
或使用 try-throw-catch
以确保 main
能够捕获所有未捕获的异常并优雅地退出。