【C++ Exceptions】在constructors内阻止资源泄露

C++不会自动清理那些“构造期间抛出exception”的对象

  • c++只会析构已经构造完成的对象;
  • 对象也只有在constructor执行完毕时才算构造完成;
  • 面对尚未完全构造好的对象,C++拒绝调用其destructor。

最佳的解决方案:使用smart point

思路:

  1. 将theImage和theAudioClip所指对象为资源,交给局部对象来管理;
  2. 不论theImage和theAudioClip作为局部变量何时释放(生命周期到),其所指资源一定得到释放;
  3. 在发生异常时,BookEntry对象被销毁(虽然还没完全构造好),同时其下所有的对象(theImage,theAudioClip)也同样会被销毁;
  4. 根据智能指针的特性,当指针销毁时,其所指资源一定会得到释放。
#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类模板:

当指向动态分配的内存的指针本身停止活动(被销毁)时,所指内存被释放掉。

(参考:C++智能指针auto_ptr、unique_ptr、shared_ptr、weak_prt详解

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值