title: How to avoid big memory allocation with std::make_shared
body: <p>Let's say that I have some arbitrary class, A:</p>
  
  <pre><code>class A {
   //... stuff
  };
  </code></pre>
  
  <p>I want to call into an external API that takes in a shared pointer to some type, like so (<strong>I cannot change this interface</strong>):</p>
  
  <pre><code>//...much later
  void foo(std::shared_ptr&lt;A&gt; _a){
      //operate on _a as a shared_ptr
  }
  </code></pre>
  
  <p>However, in the (legacy) code I'm working with, the class <code>A</code> instance I'm working with is allocated on the stack (<strong>which I cannot get around</strong>):</p>
  
  <pre><code>A a;
  //...some stuff on a
  //Now time to call foo
  </code></pre>
  
  <p>On top of this, an instance of class A is quite large, on the order of 1 GB per instance.</p>
  
  <p>I know I could call</p>
  
  <pre><code>foo(std::make_shared&lt;A&gt; a);
  </code></pre>
  
  <p>but that would allocate memory for a copy of A, which I would really like to avoid.</p>
  
  <h2>Question</h2>
  
  <p>Is there a way to hack together some call to <code>std::make_shared</code> (possibly with <code>move</code> semantics) so that I am not forced to allocate memory for another instance of class A?</p>
  
  <p>I've tried something like this:</p>
  
  <pre><code>foo(std::make_shared&lt;A&gt;(std::move(a)));
  </code></pre>
  
  <p>But from what I can tell, a new instance of <code>A</code> is still created.</p>
  
  <h3>Example code</h3>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;memory&gt;
  using namespace std;
  
  
  class A{
      public:
      A(int _var=42) : var(_var){cout &lt;&lt; "Default" &lt;&lt; endl;}
      A(const A&amp; _rhs) : var(_rhs.var){cout &lt;&lt; "Copy" &lt;&lt; endl;}
      A(A&amp;&amp; _rhs) : var(std::move(_rhs.var)){cout &lt;&lt; "Move" &lt;&lt; endl;}
      int var;
  };
  
  void foo(std::shared_ptr&lt;A&gt; _a){
      _a-&gt;var = 43;
      cout &lt;&lt; _a-&gt;var &lt;&lt; endl;
  }
  
  int main() {
      A a;
      cout &lt;&lt; a.var &lt;&lt; endl;
      foo(std::make_shared&lt;A&gt;(std::move(a)));
      cout &lt;&lt; a.var &lt;&lt; endl;
      a.var = 44;
      foo(std::make_shared&lt;A&gt;(std::move(a)));
      cout &lt;&lt; a.var &lt;&lt; endl;
      return 0;
  }
  </code></pre>
  
  <h3>Output:</h3>
  
  <blockquote>
    <p>Default <br> 42 <br> Move <br> 43 <br> 42 <br> Move <br> 43 <br> 44</p>
  </blockquote>