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

后端 未结 3 1989
清歌不尽
清歌不尽 2020-12-16 17:16

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(); }
         


        
相关标签:
3条回答
  • 2020-12-16 18:09

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

    0 讨论(0)
  • 2020-12-16 18:09

    RAII - Resource Acquisition Is Initialization

    0 讨论(0)
  • 2020-12-16 18:12

    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:

    • UDSTMR - Using Destructor Semantics To Manage Resources.
    • UTSTTC - Using The Stack To Trigger Cleanup.
    • LECLEOEIGU - Lifetime Equals Class Lifetime Or Else It Gets Ugly (the original suggestion, LECCLEOEIGU - Lifetime Equals C++ Class Lifetime Or Else It Gets Ugly, includes the language name, which I prefer to remove in this answer because the language is known).
    0 讨论(0)
提交回复
热议问题