std :: shared_ptr:未调用自定义删除器

Joh*_*n H 3 c++ shared-ptr c++11

我正在编写C++ Primer,第5版,作者提供了一个示例,使用shared_ptrs来管理可能泄漏内存的旧库中的资源,以防止它们这样做.我决定创建一个测试来查看它是如何工作的,但是在抛出异常并且(故意)没有捕获之后我的自定义删除器不会被调用:

#include <iostream>
#include <memory>
#include <string>

struct Connection {};

Connection* Connect(std::string host)
{
    std::cout << "Connecting to " << host << std::endl;
    return new Connection;
}

void Disconnect(Connection* connection)
{
    std::cout << "Disconnected" << std::endl;
    delete connection;
}

void EndConnection(Connection* connection)
{
    std::cerr << "Calling disconnect." << std::endl << std::flush;
    Disconnect(connection);
}

void AttemptLeak()
{
    Connection* c = Connect("www.google.co.uk");
    std::shared_ptr<Connection> connection(c, EndConnection);

    // Intentionally let the exception bubble up.
    throw;
}

int main()
{
    AttemptLeak();

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

它产生以下输出:

连接到www.google.co.uk

我的理解是,当一个函数退出时,无论是正常退出还是由于异常,局部变量都将被销毁.在这种情况下,这应该意味着connectionAttemptLeaks()退出时被销毁,调用它的析构函数,然后调用它EndConnection().另请注意我正在使用和刷新cerr,但这也没有给出任何输出.

我的例子或我的理解是否有问题?

编辑:虽然我已经有了这个问题的答案,但对于将来偶然发现这个问题的其他人来说,我的问题在于我对throw工作的理解.虽然下面的答案正确地说明了如何使用它,但我认为最好明确说明我(错误地)尝试使用它来"生成"未处理的异常,以测试上面的代码.

Pet*_* G. 8

Bare throw旨在用于catch块内以重新抛出捕获的异常.如果您在catch块之外使用它,terminate()将被调用并且您的程序立即结束.看看"扔"是什么 在一个拦截区外吗?

如果删除throw-statement,shared_ptr connection则超出范围并应调用删除器.如果您对使用shared_ptr(我没有;)的异常安全性有任何疑问,可以通过更改throw为显式抛出异常throw 1.