C++不会自动清理那些“构造期间抛出exception”的对象
- c++只会析构已经构造完成的对象;
- 对象也只有在constructor执行完毕时才算构造完成;
- 面对尚未完全构造好的对象,C++拒绝调用其destructor。
最佳的解决方案:使用smart point
思路:
- 将theImage和theAudioClip所指对象为资源,交给局部对象来管理;
- 不论theImage和theAudioClip作为局部变量何时释放(生命周期到),其所指资源一定得到释放;
- 在发生异常时,BookEntry对象被销毁(虽然还没完全构造好),同时其下所有的对象(theImage,theAudioClip)也同样会被销毁;
- 根据智能指针的特性,当指针销毁时,其所指资源一定会得到释放。
#include <stdio.h>
#include <iostream>
#include <memory>
using namespace std;
class Image
{
public:
Image(const string& imageDataFileName)
{
printf("Image constructor\r\n");
}
~Image()
{
printf("Image destructor\r\n");
}
};
class AudioClip
{
public:
AudioClip(const string& audioDataFileName)
{
printf("AudioClip constructor\r\n");
throw invalid_argument("throw execption for testing!");
}
~AudioClip()
{
printf("AudioClip destructor\r\n");
}
};
class BookEntry
{
public:
//使用智能指针来解决构造函数中抛出的异常
BookEntry(string &imageDataFileName, string& audioDataFileName);
~BookEntry();
private:
const unique_ptr<Image> theImage;
const unique_ptr<AudioClip> theAudioClip;
};
BookEntry::BookEntry(string &imageDataFileName, string& audioDataFileName):
theImage(imageDataFileName != "" ? new Image(imageDataFileName):0),
theAudioClip(audioDataFileName != "" ? new AudioClip(audioDataFileName):0)
{
printf("BookEntry constructor\r\n");
}
BookEntry::~BookEntry()
{
printf("BookEntry destructor\r\n");
}
int main()
{
string imageDataFileName("abc");
string audioDataFileName("def");
try
{
BookEntry bookEntry(imageDataFileName, audioDataFileName);
}
catch (invalid_argument e)
{
printf("%s\r\n", e.what());
return -1;
}
return 0;
}
//运行结果:
//Image constructor
//AudioClip constructor
//Image destructor
//throw execption for testing!
总结
auto_ptr类模板:
当指向动态分配的内存的指针本身停止活动(被销毁)时,所指内存被释放掉。