我的机器的 std::exception_ptr、std::current_exception 和 rethrow_exception 的实现是否存在内存泄漏?

Phi*_* B. 7 c++ exception std rethrow

运行以下代码时,我看到进程的内存消耗增加。我的代码中是否存在内存泄漏,std 实现中是否存在内存泄漏,或者它是预期的行为吗?它在 Windows 10 机器上运行;Visual Studio 和任务管理器都显示每分钟大约有 1MB 内存增长。

for (int i = 0; i < 10000; i++) {

    std::exception_ptr exptr = nullptr;
    std::string errmsg = "some error";
    try {
        throw std::runtime_error(errmsg.c_str());
    }
    catch (...) {
        exptr = std::current_exception();
    }

    if (exptr) {
        try {
            rethrow_exception(exptr);
        }
        catch (std::exception const& ex) {
            exptr = nullptr;
            std::cout << ex.what() << std::endl;
        }
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(10ms));
}
Run Code Online (Sandbox Code Playgroud)

当直接抛出并无延迟记录时(不使用std::exception_ptr),内存消耗不会增长。 std::exception_ptr被宣传为行为类似于智能指针,因此当重置它(将其设置为nullptr)时,底层资源应该被销毁。因此,我希望适当地释放底层异常。

Phi*_* B. 0

我发现以下内容:当我将代码复制到新项目中时,内存消耗不会增加。我比较了编译器选项,需要激活以下编译器选项以避免内存消耗增加:/EHsc

从 msvc 编译器文档中我读到: [...]默认的异常展开代码不会破坏由于异常而超出范围的 try 块之外的自动 C++ 对象。当抛出 C++ 异常时,可能会导致资源泄漏和未定义的行为。[...] 因此,不断增长的内存消耗可能是内存泄漏。