【发布时间】:2014-03-12 02:17:51
【问题描述】:
我正在阅读 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;
}
它产生以下输出:
连接到 www.google.co.uk
我的理解是,当一个函数退出时,无论是正常退出还是异常退出,局部变量都会被销毁。在这种情况下,这应该意味着connection 在AttemptLeaks() 退出时被销毁,调用其析构函数,然后调用EndConnection()。另请注意,我正在使用并刷新 cerr,但这也没有给出任何输出。
我的例子或者我的理解有问题吗?
编辑:虽然我已经有了这个问题的答案,但对于将来偶然发现这个问题的任何人来说,我的问题在于我对 throw 工作原理的理解。虽然下面的答案正确地说明了如何使用它,但我认为最好明确说明我(错误地)试图使用它来“生成”一个未处理的异常,以测试我上面的代码。
【问题讨论】:
-
总是在某处捕获异常
-
@MooingDuck 我知道。正如问题所述,我故意没有捕捉到它,以查看它的行为如何,并且它的行为不像作者所说的那样。
-
正如下面的回答所说,你对shared_ptr和析构函数有正确的理解,你理解的错误是exceptions。
-
@MooingDuck 感谢您验证我的理解。感谢您的帮助。
标签: c++ c++11 shared-ptr