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++?
#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 Initializati开发者_JAVA百科ons/Return effectively.
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 tox
inY
- pass
x
by value (or const reference), and store a copy ofx
inY
精彩评论