|
将手动资源管理封装到类中时,请使用仅管理单个资源的类。 通过保持类简单,可以降低引入资源泄漏的风险。 如有可能,请使用智能指针,如以下示例所示。 对于突出显示使用 shared_ptr 时的差异,此示例是特意模拟的,非常简单。
// old-style new/delete version
class NDResourceClass {
private:
int* m_p;
float* m_q;
public:
NDResourceClass() : m_p(0), m_q(0) {
m_p = new int;
m_q = new float;
}
~NDResourceClass() {
delete m_p;
delete m_q;
}
// Potential leak! When a constructor emits an exception,
// the destructor will not be invoked.
};
// shared_ptr version
#include <memory>
using namespace std;
class SPResourceClass {
private:
shared_ptr<int> m_p;
shared_ptr<float> m_q;
public:
SPResourceClass() : m_p(new int), m_q(new float) { }
// Implicitly defined dtor is OK for these members,
// shared_ptr will clean up and avoid leaks regardless.
};
// A more powerful case for shared_ptr
class Shape {
// ...
};
class Circle : public Shape {
// ...
};
class Triangle : public Shape {
// ...
};
class SPShapeResourceClass {
private:
shared_ptr<Shape> m_p;
shared_ptr<Shape> m_q;
public:
SPShapeResourceClass() : m_p(new Circle), m_q(new Triangle) { }
};
|
|