How to prevent member variable of Object X from going out of scope when shared_ptr of X is returned from the stack frame of a function call in C++?
<pre><code>#include &lt;iostream&gt;
#include &lt;fstream&gt;
#include &lt;map&gt;
#include &lt;vector&gt;
#include &lt;string&gt;
#include &lt;tr1/memory&gt;
#include &lt;algorithm&gt;
#include &lt;utility&gt;


class X {
  public:
    int x;

    X(){
      std::cout &lt;&lt; "Inside X cons" &lt;&lt; std::endl;
    }

    X(X&amp; _x){
      std::cout &lt;&lt; "Inside Copy cons" &lt;&lt; std::endl;
      this-&gt;x = _x.x;
    }
};

class Y {
  private:
    X&amp; xx;
  public:
    Y(X&amp;);
};

Y::Y(X&amp; x):xx(x){}

int foo(){
  X x;
  Y y(x);
};
</code></pre>

<p>In this Hypothetical case, If I had replaced Y y(x) with 
    shared_ptr(new Y(x)) and return the shared_ptr instead of int.
then x will go out of scope in the caller's frame right?
What design pattern should I use to avoid such cases and handle Initializations/Return effectively.</p>
