开发者

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++?

开发者 https://www.devze.com 2023-01-14 14:53 出处:网络
#include <iostream> #include <fstream> #include <map> #include <vector> #include <string>
#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 to x in Y
  • pass x by value (or const reference), and store a copy of x in Y
0

精彩评论

暂无评论...
验证码 换一张
取 消