title: How to use shared_ptr to supply mock object from outside?
body: <p>I want to test an app <code>Thud</code>, which will use a resource <code>Foo</code>. It will not own a concrete object but will have a pointer to a abstract resource interface (<code>IFoo</code> here). In production I will supply it with the actual resource implementation (<code>FooImpl</code>) whereas for unit test I want to send a pointer to a mock resource. How should I do this ? I've tried to write the least code just to get to point,</p>
  
  <pre><code>class IFoo
  {
  public:
      virtual bool Foo(bool) = 0;
  };
  
  class FooImpl : public IFoo
  {
  public:
      bool Foo(bool b) override
      {
          return b;
      }
  };
  
  class FooMock : public IFoo
  {
  public:
      MOCK_METHOD1(Foo, bool(bool));
  };
  
  class ThudTest : public ::testing::Test
  {
  protected:
      virtual void SetUp() {
          //foo.reset(&amp;mock); //line#1
          foo = &amp;mock; //line#2
      }
  
      FooMock mock;
      //std::shared_ptr&lt;IFoo&gt; foo; //line#3
      IFoo* foo; //line#4
  };
  
  class Thud
  {
      //std::shared_ptr&lt;IFoo&gt; fooPtr; //line#5
      IFoo* fooPtr; //line#6
  public:
      /*Thud(std::shared_ptr&lt;IFoo&gt; fooPtr_) : fooPtr{ fooPtr_ }
      {}*/ //line#7
      Thud(IFoo* fooPtr_) : fooPtr{ fooPtr_ }
      {} //line#8
      bool thud1(bool b)
      {
          return fooPtr-&gt;Foo(b);
      }
  };
  
  TEST_F(ThudTest, fooFalse)
  {
      bool b = false;
      EXPECT_CALL(mock, Foo(b)).Times(1).WillOnce(Return(false));;
  
      Thud thud(foo);
      EXPECT_FALSE(thud.thud1(b));
  }
  
  TEST_F(ThudTest, fooTrue)
  {
      bool b = true;
      EXPECT_CALL(mock, Foo(b)).Times(1).WillOnce(Return(true));;
  
      Thud thud(foo);
      EXPECT_TRUE(thud.thud1(b));
  }
  
  int main(int argc, char** argv) {
      // The following line must be executed to initialize Google Mock
      // (and Google Test) before running the tests.
      ::testing::InitGoogleMock(&amp;argc, argv);
      return RUN_ALL_TESTS();
  }
  </code></pre>
  
  <p>So for completion I've has an overloaded constructor that takes not arguement but will do the following,</p>
  
  <pre><code>Thud():fooPtr {std::make_shared&lt;FooImpl&gt;()}
  {}
  </code></pre>
  
  <p>to get the real implementation in production.
  But now how do I make the pointer point to the mock object. As you can see, I'm using GMock framework here. How to achieve this ?</p>
  
  <p>If I comment out line #2,4,6 &amp; 8 which uses a plain old raw pointer and uncomment and use line #1,3,5 &amp; 7 (using the <code>shared_ptr</code> in question here) instead, it crashes with heap corruption after the first test case.</p>
  
  <p>It works perfectly with this raw pointer.</p>