title: Dependency injection in C++
body: <p>This is also a question that I asked in a comment in one of Miško Hevery's <a href="http://misko.hevery.com/2008/11/11/clean-code-talks-dependency-injection/" rel="noreferrer">google talks</a> that was dealing with dependency injection but it got buried in the comments.</p>
  
  <p>I wonder how can the factory / builder step of wiring the dependencies together can work in C++.</p>
  
  <p>I.e. we have a class A that depends on B. The builder will allocate B in the heap, pass a pointer to B in A's constructor while also allocating in the heap and return a pointer to A.</p>
  
  <p>Who cleans up afterwards? Is it good to let the builder clean up after it's done? It seems to be the correct method since in the talk it says that the builder should setup objects that are expected to have the same lifetime or at least the dependencies have longer lifetime (I also have a question on that). What I mean in code:</p>
  
  <pre><code>class builder {
  public:
      builder() :
          m_ClassA(NULL),m_ClassB(NULL) {
      }
      ~builder() {
          if (m_ClassB) {
              delete m_ClassB;
          }
          if (m_ClassA) {
              delete m_ClassA;
          }
      }
      ClassA *build() {
          m_ClassB = new class B;
          m_ClassA = new class A(m_ClassB);
          return m_ClassA;
      }
  };
  </code></pre>
  
  <p>Now if there is a dependency that is expected to last longer than the lifetime of the object we are injecting it into (say ClassC is that dependency) I understand that we should change the build method to something like:</p>
  
  <pre><code>ClassA *builder::build(ClassC *classC) {
      m_ClassB = new class B;
      m_ClassA = new class A(m_ClassB, classC);
      return m_ClassA;
  }
  </code></pre>
  
  <p>What is your preferred approach?</p>