为什么会想到这个问题?因为我总是不自觉地将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;
}
}

c++ what happens when a constructor throws an exception and leaves the object in an inconsistent state?的更多相关文章

  1. In p = new Fred(), does the Fred memory “leak” if the Fred constructor throws an exception?

    No. If an exception occurs during the Fred constructor of p = new Fred(), the C++ language guarantee ...

  2. org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.hs.model.StudentModel]: No default constructor found; nested exception is java.lang.NoSuchMethodException: c

    root cause org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [c ...

  3. throws/throw Exception 异常应用

    throws通常用于方法的声明,当方法中发生异常的时候,却不想在方法中对异常进行处理的时候,就可以在声明方法时, 使用throws声明抛出的异常,然后再调用该方法的其他方法中对异常进行处理(如使用tr ...

  4. Nhibernate 4.0 教程入门

    Nhibernate 4.0 教程 目录 1.      下载Nhibernate 4.04. 1 2.      入门教程... 2 3.      测试项目详解... 3 4.      总结.. ...

  5. spring源码分析(一)IoC、DI

    创建日期:2016.08.06 修改日期:2016.08.07 - 2016.08.12 交流QQ:992591601 参考书籍:<spring源码深度解析>.<spring技术内幕 ...

  6. Static Constructors

    A static constructor is used to initialize any static data, or to perform a particular action that n ...

  7. (C++) Interview in English. - Constructors/Destructors

    Constructors/Destructors. 我们都知道,在C++中建立一个类,这个类中肯定会包括构造函数.析构函数.复制构造函数和重载赋值操作:即使在你没有明确定义的情况下,编译器也会给你生成 ...

  8. How a C++ compiler implements exception handling

    Introduction One of the revolutionary features of C++ over traditional languages is its support for ...

  9. xmlhttp

    File an issue about the selected textFile an issue about the selected text XMLHttpRequest Living Sta ...

随机推荐

  1. [CF911G]Mass Change Queries

    题目大意: 给你一个长度为n的数列a,按顺序进行以下m次操作,每次将区间[l,r]中的所有x变成y,问最后数列是怎样的. 思路: 线段树. 每个线段树结点上维护当前区间每个数分别会变成多少.时间复杂度 ...

  2. python基础-文件处理与函数

    1. 文件处理 1.1 文件处理流程 1.打开文件,得到文件句柄并赋值给一个变量 2.通过句柄对文件进行操作 3.关闭文件 1.2 文件读取模式r r文本模式的读,在文件不存在,不会创建新文件 f = ...

  3. 将Java程序打jar包并运行

    1)接着上篇博客继续说手动编译之后,将代码打成jar包,然后直接“java -jar lz.jar"运行不成功的问题.还是先上代码: 这个是Demo类: package org.lz.dem ...

  4. Solr6 +mmseg4j+IK-Analyzer + SQLserver +DIH 完全配置

    如今做任何一个系统都有搜索,而搜索界有著名的三剑客: solr/elasticsearch/sphinx solr/elasticsearch 为同一类的,都是基于lucene开发的产品,本人也早在几 ...

  5. asp.net mvc视图引擎

    继上周介绍了Razor之后,ASP.NET MVC 现在已有四种主要的视图引擎.其他三种引擎是Spark.NHaml和传统的ASPX文件模板.本文将大致介绍这四种引擎,并着重讨论新的Razor引 擎. ...

  6. easyui datagrid加载成功之后选定并获取首行数据

    //加载成功之后,选定并获取首行数据 onLoadSuccess:function(data){ alert("grid加载成功"); var rows=$('test').dat ...

  7. css3动画和JS+DOM动画和JS+canvas动画比较

    css3兼容:IE10+.FF.oprea(animation):safari.chrome(-webkit-animation) js+dom:没有兼容问题: js+canvas:IE9+:(性能最 ...

  8. IE8 XSS Filter Bypass

    漏洞说明:IE8是微软新推出的一款浏览器,其对CSS2.1的完整支持,HTML5的支持,内置开发工具等等.IE8在浏览器安全性上有非常大的改进,内置了一款无法卸载的Xss Filter,对非持久型跨站 ...

  9. Java计算两个日期相差的天数

    import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; impor ...

  10. 分享一个仅0.7KB的jQuery文本框输入提示插件

    由于项目需要,找过几个jQuery文本框输入提示插件来用,但总是有不满意的地方,要么体积较大,要么使用不便,要么会出现把提示文字作为文本框的值的情况.于是我们自己的开发团队制作了这个最精简易用的输入提 ...