title: Should safe pointers be used in strategy pattern?
body: <p>Given a typical strategy pattern</p>
  
  <pre><code>class Strategy
  {
  public:
      virtual int execute() const = 0;
  }
  
  class StrategyA : public Strategy
  {
  public:
      int execute() const override;
  }
  
  class StrategyB : public Strategy
  {
  public:
      int execute() const override;
  }
  </code></pre>
  
  <p>I believe the 'pre-C++11' way to implement a context class would be something like</p>
  
  <pre><code>class ContextRaw
  {
  public:
      ContextRaw(Strategy* the_strategy);
      ~ContextRaw(); // Should this delete the_strategy_?
      int execute() const;
  private:
      Strategy* the_strategy_;
  }
  </code></pre>
  
  <p>To me, in this design it's not clear if <code>Context</code> should take responsibility for <code>Strategy</code>, and unless there is clear documentation stating otherwise, bad things might happen if it does</p>
  
  <pre><code>void trouble()
  {
      StrategyA a_concrete_strategy;
      ContextRaw a_context(&amp;a_concrete_strategy); // Oops, Context may try to delete stack variable
  }
  
  void more_trouble()
  {
      Strategy* a_concrete_strategy = new StrategyA;
      ContextRaw* a_context       = new ContextRaw(a_concrete_strategy);
      ContextRaw* another_context = new ContextRaw(a_concrete_strategy);
      delete a_context;
      std::cout &lt;&lt; another_context.execute() &lt;&lt; std::endl; // Oops, the_strategy is deleted
  }
  </code></pre>
  
  <p>In light of safe-pointers, should it now be preferable to inject a safe pointer, and have <code>Context</code> take ownership of the <code>Strategy</code>?</p>
  
  <pre><code>class ContextUnique
  {
  public:
      ContextUnique() = delete;
      ContextUnique(std::unique_ptr&lt;Strategy&gt; the_strategy);
      ~ContextUnique();
      int execute() const;
  private:
      std::unique_ptr&lt;Strategy&gt; the_strategy_;
  }
  </code></pre>
  
  <p>or if <code>Strategy</code> can be shared amongst different <code>Context</code>?</p>
  
  <pre><code>class ContextShared
  {
  public:
      ContextShared() = delete;
      ContextShared(std::shared_ptr&lt;Strategy&gt; the_strategy);
      ~ContextShared();
      int execute() const;
  private:
      std::shared_ptr&lt;Strategy&gt; the_strategy_;
  }
  </code></pre>
  
  <p>This design of course introduces problems of it's own, in particular only dynamically allocated <code>Strategy</code>'s can be injected into <code>Context</code>.</p>