Pay close attention to manage multiple resource in one object - C++11, 24 of n
来源:互联网 发布:免费领取比特币软件 编辑:程序博客网 时间:2024/04/30 22:35
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_;
};
- Pay close attention to manage multiple resource in one object - C++11, 24 of n
- pay attention to \r \n
- Pay Attention to the Reference of Java
- Zhao Jinglei: ReadSense Ltd Pay more attention to the commercialization of the ground, research AI c
- Zhao Jinglei: ReadSense Ltd Pay more attention to the commercialization of the ground, research AI c
- Zhao Jinglei: ReadSense Ltd Pay more attention to the commercialization of the ground, research AI c
- Zhao Jinglei: ReadSense Ltd Pay more attention to the commercialization of the ground, research AI c
- Pay attention of my friends
- Pay attention to tech trend
- Manage objective c object memory in Block
- Please pay more attention to the character set of your database
- about struts~~~pay attention to that~~~
- Pay attention to the calling convention!
- [c++]错误multiple types in one declaration
- PAY ATTENTION
- How to define multiple controllers for one view in angularJS?
- How to manage multiple passwords on Linux
- Pay attention to pointers: always initialize your pointers
- “Invalid layout of preloaded class”问题解决
- 关于浏览器的好文章
- 解决union慢问题(ORA-17410)
- 测试点总结(不断更新中)
- Linux内核启动过程分析
- Pay close attention to manage multiple resource in one object - C++11, 24 of n
- WPF中的ListBox的用法
- 32位和64位下的sizeof
- ios逆向
- win7(旗舰版)VC添加控件显示不支持此接口
- 进入录音的时候有一条闪显的横条
- 程序猿十大电影盘点
- MFC程序中如何接受命令行参数
- 使用ContentProvider管理多媒体内容