title: c++ Dependency Injection: Object lifetimes?
body: <p>I'm coming from C# and trying to translate some of my practices into C++.  I've used dependency injection in various places throughout my code using raw pointers.  Then I decide to replace the raw pointers with std::shared_ptr's.  As part of that process it was suggested that I consider using stack allocated automatic variables rather than dynamically allocating them (see <a href="https://stackoverflow.com/questions/7971895/c-can-i-use-stdunique-ptr-with-dependency-injection">this question</a> although that question was in the context of unique_ptr so maybe that is different).</p>
  
  <p>I believe the below example shows the use of automatic variables.</p>
  
  <pre><code>class MyClass
  { 
  public:
     MyClass(ApplicationService&amp; app): appService_(app)
     {
     }
  
     ~MyClass()
     {
          appService_.Destroy(something);
  
     }
  private:   
     ApplicationService&amp; appService_;
  }
  
  class ConsumerClass
  {
      DoSomething()
      {
          CustomApplicationService customAppService;
          MyClass myclass(customAppService);
          myclass...
      }
  }
  </code></pre>
  
  <p>In the above example, when customAppservice and myclass go out of scope how do I know which will be destroyed first?  If customAppService is destroyed first than the MyClass destructor will fail.  Is this a good reason to use shared_ptr instead in this scenario or is there a clean way around this?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>ApplicationService is a class that is a wrapper around global functions needed to interact with a 3rd party library that my code uses.  I have this class as I believe it's the standard way to support unit testing and stubbing/mocking of free standing functions.  This class simply delegates calls to the corresponding global functions. The call appService_.Destroy(something); is actually destroying an object used by each specific instance of MyClass not destroying anything do with the Application class itself.</p>