【发布时间】:2016-10-13 18:03:25
【问题描述】:
我读到智能指针在构造函数产生一些异常的情况下很有帮助。
问题是构造函数在生成异常之前获得了一些资源,但没有调用析构函数(并且资源永久繁忙)。
但我无法正确理解它。 我的代码:
#include <memory>
#include <iostream>
class resOwner {
public:
resOwner() {
std::cout << "Map some huge resources\n";
throw "hi";
}
~resOwner() {
std::cout << "Free some huge resources\n";
}
};
class normal : resOwner {
};
int main (){
try {
std::shared_ptr<resOwner> k (new resOwner());
} catch (...) {}
}
输出为Map some huge resources。
如何用智能指针解决这种资源泄漏?
【问题讨论】:
-
别担心 - 如果 c-tor 抛出,内存会被释放 - 没有智能指针的合作 - 请参阅 stackoverflow.com/questions/1674980/…
-
resOwner拥有的任何资源都必须是某种智能指针unique_ptr或shared_ptr等。否则您将最终导致资源泄漏,因为您计划在析构函数中清理的任何内容都不会被调用。 -
值得指出的是,如果单个构造函数运行完成(构造函数委托)并且委托构造函数抛出,则将调用对象的析构函数。
标签: c++ memory-leaks shared-ptr smart-pointers resource-leak