tags:

views:

27

answers:

1
#include <iostream>
#include <fstream>
#include <map>
#include <vector>
#include <string>
#include <tr1/memory>
#include <algorithm>
#include <utility>


class X {
  public:
    int x;

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

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

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

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

int foo(){
  X x;
  Y y(x);
};

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.

A: 

As you already pointed out, it is not possible to hold a reference to a temporary object and expect that reference to be valid after the temporary object goes out of scope. Alternatives are:

  • create x on the heap, and store a (shared) pointer to x in Y
  • pass x by value (or const reference), and store a copy of x in Y
Ton van den Heuvel