Caveats:
- if constructor (at any point, say in the body of constructor) throws, the object's desctructor will NEVER be invoked, because the compiler can't tell what's the state of the object under construction like.
- If constructor throws, all of the fully constructed base subobjects and data members will be destructed.
- C++11, if the non-delegating constructor for an object has completed execution and a delegating constructor for that object exists with an exception, the object's destructor will be invoked.
- Example:
class MayLeak {
public:
MayLeak(int x, int y): a_(nullptr), b_(nullptr) {
a_ = new A(x);
b_ = new B(y); // if new B(y) throws, a_ is leaked
}
~MayLeak() {
delete b_;
delete a_;
}
private:
A a_;
B b_;
};
Preferred fix:
class MayLeak {
public:
MayLeak(): a_(make_shared<A>(x)), b_(make_shared<B>(y)) {
// if make_unique<B>() throws, a_ is also desctructed, no leak
}
private:
shared_ptr<A> a_;
shared_ptr<B> b_;
};
Another fix in C++11:
class MayLeak {
public:
MayLeak() : a_(nullptr), b_(nullptr) {
}
MayLeak(int x, int y): MayLeak() {
// When non-delegating MayLeak() constructor finishes,
// ~MayLeak destructor will be guaranteed to be invoked by stanadard
a_ = new A(x);
b_ = new B(y); // if new B(y) throws, a_ is NOT leaked, because ~MayLeak will be invoked.
}
~MayLeak() {
delete b_;
delete a_;
}
private:
A *a_;
B *b_;
};
本文探讨了C++中构造函数与析构函数执行期间可能遇到的问题,特别是当构造函数抛出异常时如何避免内存泄漏。通过示例展示了两种解决方法:使用智能指针管理和委托构造函数。
1132

被折叠的 条评论
为什么被折叠?



