为什么会想到这个问题?因为我总是不自觉地将c++和java进行对比。java对这种情况的处理方式是constructor返回一个null,然后已经构造的objects交给Garbage Collector处理,那么c++没有Garbage Collector,会是怎么样的一种情况呢?

为了找到这个问题的答案,我做了个小实验,代码见main.cpp, Box.h, Box.cpp

运行之前,我的设想是box->b的值为"NULL",因此程序输出如下:

e.what() : a < 0

b == NULL

而事实是,在输出e.what() : a < 0之后,程序便崩溃了

打上断点一瞧,执行到box->dostuff()里面的时候,这些主存地址都已经不可访问(也就是说已经被操作系统回收了,不再属于这个程序的可访问主存范围),截图如下:

根据c++ primer 4th edition section 17.1.2 "Exceptions and Constructors" 我引用如下:

If an exception occurs while constructing an object, then the object might be only partially constructed. Some of its members might have been initialized, and others might not have been initialized before the exception occurs. Even if the object is only partially constructed, we are guaranteed that the constructed members will be properly destroyed.

我最开始以为加粗的句子是说要让我们自己来guarantee that the constructed memebers will be properly destroyed,原来这个工作不需要我们做(?)。然后我又重新修改了程序来验证这一点——"we are guaranteed that the constructed members will be properly destroyed.",见main1.cpp,Box1.h,Box1.cpp

但是执行的结果如下:

也就是说,what和why所占用的主存空间泄漏了,memory leak

也就是说,c++ primer所说的“we are guaranteed that the constructed members will be properly destroyed.不适用于new出来的object!

怎么办?参考这个问题:http://stackoverflow.com/questions/188693/is-the-destructor-called-if-the-constructor-throws-an-exception

所以改写程序为:main2.cpp,Box2.h,Box2.cpp,运行结果如下(完美解决!):

至于auto_ptr的实现方法,之前我写过一篇随笔(http://www.cnblogs.com/qrlozte/p/4095618.html),其实就是c++ primer 4th edition section 13.5.1 "Defining Smart Pointer Classes"所陈述的内容,大概的思路都在c++ primer的这个章节里面了,值得一看!

main.cpp

 #include "Box.h"

 #include <iostream>
#include <stdexcept> using namespace std; int main() {
Box *box = NULL;
try {
box = new Box(-);
} catch (invalid_argument &e) {
cout << "e.what() : " << e.what() << endl;
box->dostuff();
}
if (box != NULL) delete box;
return ;
}

Box.h

 #ifndef BOX_H
#define BOX_H class Box
{
public:
Box(const int &a);
~Box();
void dostuff(); private: int a;
int *b;
}; #endif // BOX_H

Box.cpp

 #include "Box.h"

 #include <iostream>
#include <stdexcept> using namespace std; Box::Box(const int &_a): a(_a), b(NULL)
{
if (a < )
throw invalid_argument("a < 0");
b = new int();
cout << "Box created" << endl;
} Box::~Box()
{
if (b != NULL) delete b;
cout << "Box destroyed" << endl;
} void Box::dostuff() {
if (b == NULL) {
cout << "b == NULL" << endl;
}
else {
cout << "b = " << b << endl;
}
}

main1.cpp

 #include "Box.h"

 #include <iostream>
#include <stdexcept> using namespace std; int main() {
Box *box = NULL;
try {
box = new Box(-);
} catch (invalid_argument &e) {
cout << "e.what() : " << e.what() << endl;
// box->dostuff();
}
if (box != NULL) delete box;
return ;
}

Box1.h

 #ifndef BOX_H
#define BOX_H #include <memory> class Bottle {
public:
Bottle();
~Bottle();
}; class Hat {
public:
Hat();
~Hat();
}; class Box
{
public:
Box(const int &a);
~Box();
void dostuff(); private: class What;
class Why; int a;
Bottle bottle;
Hat hat;
What *what;
Why *why;
int *b;
}; #endif // BOX_H

Box1.cpp

 #include "Box.h"

 #include <iostream>
#include <stdexcept> using namespace std; class Box::What {
public:
What() { cout << "What created" << endl; }
~What() { cout << "What destroyed" << endl; }
}; class Box::Why {
public:
Why() { cout << "Why created" << endl; }
~Why() { cout << "Why destroyed" << endl; }
}; Bottle::Bottle() { cout << "Bottle created" << endl; }
Bottle::~Bottle() { cout << "Bottle destroyed" << endl; } Hat::Hat() { cout << "Hat created" << endl; }
Hat::~Hat() { cout << "Hat destroyed" << endl; } // Pay attention to the order of the initializer: the same as the declaration
// order, otherwise the compiler will give warnings (there's a reason for that)
// the reason is the compiler always initializes data members following the order
// in which they're declared
Box::Box(const int &_a): a(_a), what(new What()), why(new Why()), b(NULL)
{
if (a < )
throw invalid_argument("a < 0");
b = new int();
cout << "Box created" << endl;
} // Notice the order of deletes: It's BETTER be the reverse order as they're created
// Without the right definition of destructor, when exception thrown from the constructor
// members cannot be destroyed properly. (Of course, also the same in normal situation).
Box::~Box()
{
if (b != NULL) delete b;
if (why != NULL) delete why;
if (what != NULL) delete what;
cout << "Box destroyed" << endl;
} void Box::dostuff() {
if (b == NULL) {
cout << "b == NULL" << endl;
}
else {
cout << "b = " << b << endl;
}
}

main2.cpp

 #include "Box.h"

 #include <iostream>
#include <stdexcept> using namespace std; int main() {
Box *box = NULL;
try {
box = new Box(-);
} catch (invalid_argument &e) {
cout << "e.what() : " << e.what() << endl;
// box->dostuff();
}
if (box != NULL) delete box;
return ;
}

Box2.h

 #ifndef BOX_H
#define BOX_H #include <memory> class Bottle {
public:
Bottle();
~Bottle();
}; class Hat {
public:
Hat();
~Hat();
}; class Box
{
public:
Box(const int &a);
~Box();
void dostuff(); private: class What;
class Why; int a;
Bottle bottle;
Hat hat;
std::auto_ptr<What> what;
std::auto_ptr<Why> why;
int *b;
}; #endif // BOX_H

Box2.cpp

 #include "Box.h"

 #include <iostream>
#include <stdexcept> using namespace std; class Box::What {
public:
What() { cout << "What created" << endl; }
~What() { cout << "What destroyed" << endl; }
}; class Box::Why {
public:
Why() { cout << "Why created" << endl; }
~Why() { cout << "Why destroyed" << endl; }
}; Bottle::Bottle() { cout << "Bottle created" << endl; }
Bottle::~Bottle() { cout << "Bottle destroyed" << endl; } Hat::Hat() { cout << "Hat created" << endl; }
Hat::~Hat() { cout << "Hat destroyed" << endl; } // Pay attention to the order of the initializer: the same as the declaration
// order, otherwise the compiler will give warnings (there's a reason for that)
// the reason is the compiler always initializes data members following the order
// in which they're declared
Box::Box(const int &_a): a(_a), what(new What()), why(new Why()), b(NULL)
{
if (a < )
throw invalid_argument("a < 0");
b = new int();
cout << "Box created" << endl;
} // Notice the order of deletes: It's BETTER be the reverse order as they're created
// Without the right definition of destructor, when exception thrown from the constructor
// members cannot be destroyed properly. (Of course, also the same in normal situation).
Box::~Box()
{
if (b != NULL) delete b;
if (why.get() != NULL) why.reset(NULL); // might be unnecessary, see auto_ptr's documentation
if (what.get() != NULL) what.reset(NULL);
cout << "Box destroyed" << endl;
} void Box::dostuff() {
if (b == NULL) {
cout << "b == NULL" << endl;
}
else {
cout << "b = " << b << endl;
}
}

最新文章

  1. MAX(A,B)
  2. 62.在cdc文件上某些例化模块看不到的原因
  3. asp.net MVC3 + JQuery 的ajax简单使用
  4. PCL—综述—三维图像处理
  5. apache访问控制设置
  6. 应用层协议系列(两)——HTTPserver之http协议分析
  7. mongodb安装 win7版
  8. linux环境下根据文件的某一列进行去重
  9. 配置struts2拦截器
  10. mongodb在windows下安装启动
  11. linux中一些简便的命令之sort
  12. SpringBoot集成mybatis配置
  13. Windows Internals 笔记——CreateProcess
  14. style标签下的CSS代码的显示与实时编辑
  15. HTTP学习---TCP三次握手和四次挥手
  16. [ASP.NET]初试Web API
  17. Python 文件 writelines() 方法
  18. 记一次常规的Mysql数据库访问的时间分析
  19. lua常用操作
  20. linux 查看文件夹文件大小数目等信息

热门文章

  1. 【模拟】洛谷 P1328 NOIP2014提高组 day1 T1 生活大爆炸版石头剪刀布
  2. [AGC012F]Prefix Median
  3. 6.2(java学习笔记)字节流
  4. Javascript常见设计模式解析
  5. 转载:win10 下安装Oracle 11g(问题:环境不满足最低要求)
  6. NET PROVIDER 连接 Oracle数据库
  7. C++发送HTTP请求---亲测可行(转)
  8. spring+mybatis项目启动报错Initializing Spring root WebApplicationContext
  9. [Python爬虫] 之二十五:Selenium +phantomjs 利用 pyquery抓取今日头条网数据
  10. php核心技术与最佳实践知识点(下)