我正在学习《C++ Primer第五版》的内容,本书中作者提供了一个例子,用于使用shared_ptr管理资源以避免内存泄漏。我决定创建一个测试来了解其工作原理。但是,在异常抛出且未被捕获时,我的自定义删除器并没有被调用:
它会产生以下输出:
我的示例有问题,还是我的理解有误? 编辑:虽然我已经得到了这个问题的答案,但对于未来遇到这个问题的其他人来说,我的问题在于我对
#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
AttemptLeaks()
退出时销毁connection
,调用其析构函数,然后应该调用EndConnection()
。请注意,我正在使用和刷新cerr
,但也没有输出任何内容。我的示例有问题,还是我的理解有误? 编辑:虽然我已经得到了这个问题的答案,但对于未来遇到这个问题的其他人来说,我的问题在于我对
throw
的工作原理的理解错误。尽管以下答案正确地说明了如何使用它,但我认为最好明确地表明,我(错误地)试图使用它来“生成”未处理的异常,以测试上面的代码。