为什么会想到这个问题?因为我总是不自觉地将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. 【并查集】bzoj2054 疯狂的馒头

    因为只有最后被染上的颜色会造成影响,所以倒着处理,用并查集维护已经染色的区间的右端点,即fa[i]为i所在的已染色区间的右端点,这样可以保证O(n)的复杂度. #include<cstdio&g ...

  2. 【可持久化Trie】【set】bzoj3166 [Heoi2013]Alo

    枚举每个数,计算以其为次大数的最大区间,显然,只需要用这个区间的答案 对 答案进行更新即可. 找到每个数右侧.左侧第1.2个比它大的数,然后分类讨论一下即可. 找到的过程中把数sort以后,从大到小把 ...

  3. 【神奇の做法】bzoj2456 mode

    题解:http://www.tuicool.com/articles/BfQBzif #include<cstdio> using namespace std; int n,x,ans,t ...

  4. 【费用流】BZOJ1061[NOI2008]-志愿者招募

    [题目大意] 一个项目需要n天完成,其中第i天至少需要Ai个人.共有m类人可以招募,其中第i类可以从第Si天做到第Ti天,每人的招募费用为Ci元.求最小招募费用. [思路] byvoid神犇的建图详解 ...

  5. python3开发进阶-Web框架的前奏

    我们可以这样理解:所有的Web应用本质上就是一个socket服务端,而用户的浏览器就是一个socket客户端. 这样我们就可以自己实现Web框架了. 1.自定义web框架 import socket ...

  6. 1.10(java学习笔记)super关键字

    supe主要是调用父类中被重写的方法及属性. 用下列代码那说明: package cn.hcf.TestSuper; public class TestSuper { public static vo ...

  7. 【MySQL笔记】: unable to connect to remote host. catalog download has failed.

    安装完MySQL之后,它每天凌晨启动一个Intaller任务,甚是烦人:   这是一个Windows的计划服务,在这里删除即可,开始/附件/系统工具/任务计划程序,把mysql的定时任务计划取消/删除 ...

  8. 移动端与PHP服务端接口通信流程设计(增强版)

    前面讲过:移动端与PHP服务端接口通信流程设计(基础版) 对于 api_token 的校验,其安全性还可再增强: 增强地方一: 再增加2张表,一个接口表,一个授权表,设计参考如下: 接口表 字段名 字 ...

  9. Google开源C++单元测试框架Google Test

    1.玩转Google开源C++单元测试框架Google Test系列(gtest)之一 - 初识gtest 2.玩转Google开源C++单元测试框架Google Test系列(gtest)之二 - ...

  10. linux 账户锁与解锁

    ,sudo passwd -l user 锁住user帐号,su 已经不能切换到user下. 2,sudo passwd -u user 解锁user帐号,su可以切换到user下. 3,如果不小心把 ...