tags:

views:

210

answers:

3

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.

+17  A: 

RAII - Resource Acquisition Is Initialization

Jonathan Leffler
though typically you'd use a smart pointer to do the RAII for you rather than code it yourself
jk
Not necessarily. Writing the RAII class yourself gives you much better control over lifetime management for the resource. Smart pointers are just one of many possible examples of RAII. The idiom covers *far* more than `boost::shared_ptr`
jalf
+9  A: 

The answer to your question is RAII (Resource Allocation 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);
         this->swap(tmp);
         return *this;
     }
    ~A()
     {
         delete m_b;
     }
     void swap(A& dst) throw ()
     {
         std::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).

Martin York
Why is his example leaky? He allocated on constructor and deallocates on destructor
Edison Gustavo Muenz
Because of the compiler generated copy constructor.
Martin York
"owns a raw pointer" should probably be expanded to "or a resource handle of any other kind". The same applies for file handles, sockets, database connections or any other resource whose lifetime has to be managed.
jalf
Btw, this really shows the power of "the fastest gun in the west" syndrome. This answer is by far more complete and detailed, but because the other one is at the top, it's getting all the upvotes...
jalf
+1  A: 

It's RAII - Resource Allocation Is Initialization, although some of us have suggested much better acronyms like UCDSTMR - Using C++ Destructor Semantics To Manage Resources or UTSTTC - Using The Stack To Trigger Cleanup.

Daniel Daranas