避免内存泄漏的C ++习惯用法? [英] C++ idiom to avoid memory leaks?

查看:60
本文介绍了避免内存泄漏的C ++习惯用法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码中,如果意外地多次调用 Info :: addPart1(),则会发生内存泄漏:

In the following code, there is a memory leak if Info::addPart1() is called multiple times by accident:

typedef struct
{
}part1;

typedef struct
{
}part2;

class Info
{
    private:
    part1* _ptr1;
    part2* _ptr2;    

    public:
    Info()
    {
      _ptr1 = _ptr2 = NULL;
    }

    ~Info()
    {
      delete _ptr1; 
      delete _ptr2;
    }

    addPart1()
    {
       _ptr1 = new part1;         
    }

    addPart2()
    {
      _ptr2 = new part2;         
    }   
};


Info _wrapper;
_wrapper.addPart1();
_wrapper.addPart2();

是否有C ++惯用法来处理此问题?

Is there a C++ idiom to handle this problem ?

我可以这样重写 addPart1 addPart2 来捍卫MLK

I could rewrite addPart1 and addPart2 like this to defend the MLK

addPart1()
{
  if(_ptr1 != NULL) delete _ptr1;
  _ptr1 = new part1;         
}

这是一个好的解决方案吗?

Is that a good solution?

推荐答案

使用智能指针,例如 auto_ptr 很难使用,您需要注意这一点.

Use a smart pointer such as boost:shared_ptr , boost:scoped_ptr is recommended to manage the raw pointer. auto_ptr is tricky to work with, you need pay attention to that.

这篇关于避免内存泄漏的C ++习惯用法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆