title: Storing pointer of singleton in class
body: <p>I'm debugging some code and I ran across this snippet that was crashing, the problem is that the singleton pointer and the local pointer are not the same address. I'm not sure why that is.</p>
  
  <p>The code roughly looks like this:</p>
  
  <pre><code>class B;
  
  class I_A : public std::enable_shared_from_this&lt;I_A&gt; {
      public:
      virtual std::shared_ptr&lt;B&gt; make() = 0;
  };
  
  class A : public I_A {
    public:
      std::shared_ptr&lt;B&gt; make() override {
          return std::make_shared&lt;B&gt;(shared_from_this());   
      }
  };
  
  static std::shared_ptr&lt;I_A&gt; getInstance() {
      static std::shared_ptr&lt;I_A&gt; ptr;
      if(!ptr) {
          std::cout &lt;&lt; "Making new instance\n";
          ptr = std::make_shared&lt;A&gt;();   
      }
      std::cout &lt;&lt; "Ptr is " &lt;&lt; ptr &lt;&lt; '\n';
      return ptr;
  }
  
  class B {
      public:
      B(const std::shared_ptr&lt;I_A&gt;&amp; ptr) : ptr(ptr) {
          std::cout &lt;&lt; "In B() " &lt;&lt; ptr &lt;&lt; '\n';
      }
  
      void foo() {
          std::cout &lt;&lt; "B::ptr " &lt;&lt; ptr &lt;&lt; '\n';
          assert(ptr == getInstance());   
      }
  
      private:
          const std::shared_ptr&lt;I_A&gt;&amp; ptr; // Potential problem here
  };
  
  
  int main() {
      auto bPtr = getInstance()-&gt;make();
      bPtr-&gt;foo();
  }
  </code></pre>
  
  <p>But if I store a copy of <code>shared_ptr&lt;I_A&gt;</code> in B instead of storing a ref, everything works fine.</p>
  
  <p>If my understanding is correct, the singleton should never change the address, but the <code>B::ptr</code> and <code>getInstance()</code> have different addresses.</p>
  
  <p>Any idea why that is?</p>