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

    import javax.swing.JOptionPane; public class Population{ public static void main(String[] args){ int ...

  2. 从系统相册中选择GIF图片上传到服务器

    -(void)assetPickerController:(ZYQAssetPickerController *)picker didFinishPickingAssets:(NSArray *)as ...

  3. winfrom向窗体中拖放图片并显示

    首先要设置窗体的AllowDrop属性为true.然后在窗体的DragEnter事件中添加如下代码:调用自定义的显示图片的方法. #region "在用鼠标将某项拖放到区域时事件" ...

  4. IIS 7 网站权限问题

    IIS7 应用程序池[标识]为[ApplicationPoolIdentity] 给程序目录赋权限: IUSER IIS AppPool\[应用程序池名]

  5. php之防注入程序绕过浅谈

    <?php/*判断传递的变量是否含有非法字符如:$_POST/$_GET功能:SQL防注入系统*/ //屏蔽错误提示error_reporting(7); //需要过滤的字符 $ArrFiltr ...

  6. fl2440字符设备led驱动

    首先要明白字符设备驱动注册的基本流程 当我们调用insomd命令加载驱动后,驱动程序从module_init函数开始执行:硬件初始化 -> 申请主次设备号 -> 定义fops(file_o ...

  7. CSS中样式

    CSS是Cascading Style Sheets的简称,中文称为层叠样式表,用来控制网页数据的表现,可以使网页的表现与数据内容分离.要想让CSS对网页内容有效果,必须将CSS代码引入网页,通常有四 ...

  8. 2017.11.30 tomcat远程调试

    参考来自:http://blog.csdn.net/afgasdg/article/details/9236877 1.jpda 有两种方式,一种是修改tomcat的catalina.bat来配置jp ...

  9. hdoj-1213-How Many Tables【并查集】

    How Many Tables Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Tot ...

  10. 倍福TwinCAT(贝福Beckhoff)常见问题(FAQ)-人机界面快速入门 TC3

    右击添加一个PLC项,注意不要用中文   右击VISUs,添加一个视图对象   在POUs中打开MAIN,然后添加代码(定义了一个BOOL和一个INT类型变量)   工具箱中得到一个textfield ...