Pattern name for create in constructor, delete in destructor (C++)

醉酒当歌 提交于 2019-11-29 03:59:42
Martin York

The answer to your question is RAII (Resource Acquisition Is Initialization).

But your example is dangerous:

Solution 1 use a smart pointer:

class A
{
  public:
     A(): m_b(new B) {}
  private:
     boost::shared_ptr<B> m_b;
};

Solution 2: Remember the rule of 4:
If your class contains an "Owned RAW pointer" then you need to override all the compiler generated methods.

class A
{
  public:
     A():              m_b(new B)           {}
     A(A const& copy): m_b(new B(copy.m_b)) {}
     A& operator=(A const& copy)
     {
         A  tmp(copy);
         swap(tmp);
         return *this;
     }
    ~A()
     {
         delete m_b;
     }
     void swap(A& dst) throw ()
     {
         using std::swap;
         swap(m_b, dst.m_b);
     }
  private:
     B* m_b;
};

I use the term "Owned RAW Pointer" above as it is the simplest example. But RAII is applicable to all resources and when your object contains a resource that you need to manage ('Owned RAW Poiner', DB Handle etc).

RAII - Resource Acquisition Is Initialization

Daniel Daranas

This technique is best known as RAII - Resource Allocation Is Initialization. It has its own tag on this site.

Alternative. more intuitive names have been suggested, in particular:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!