Pattern name for create in constructor, delete in

2019-01-24 06:30发布

Traditionally, in C++, you would create any dependencies in the constructor and delete them in the destructor.

class A
{
 public:
    A() { m_b = new B(); }
    ~A() { delete m_b; }
 private:
    B* m_b;
};

This technique/pattern of resource acquisition, does it have a common name?
I'm quite sure I've read it somewhere but can't find it now.

Edit:
As many has pointed out, this class is incomplete and should really implement a copy constructor and assignment operator.
Originally, I intentionally left it out since it wasn't relevant to the actual question: the name of the pattern. However, for completeness and to encourage good practices, the accepted answer is what it is.

3条回答
该账号已被封号
2楼-- · 2019-01-24 06:56

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:

查看更多
一纸荒年 Trace。
3楼-- · 2019-01-24 07:10

RAII - Resource Acquisition Is Initialization

查看更多
家丑人穷心不美
4楼-- · 2019-01-24 07:13

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).

查看更多
登录 后发表回答