Home > Software engineering >  Pass an object with this to another object
Pass an object with this to another object

Time:10-21

If I have a Y which has a member pointer to X, how can I make an instance of Y in X?

I thought about passing it somewhat like this:

#include <memory>

struct X;
struct Y 
{    
    Y(int n, std::shared_ptr<X> x) 
        : n_(n)
        , x_(x)
    {}

    std::shared_ptr<X> x_;
    int n_;
};
    
struct X 
{
    void d()
    {
        auto y = std::make_shared<Y>(20, this);
    } 
};
    
int main()
{
    return 0;
}

CodePudding user response:

Here's a possible solution using std::enable_shared_from_this.

#include <iostream>
#include <memory>

using namespace std;

struct X;

struct Y 
{    
    Y(int n, std::shared_ptr<X> x):
    n_(n),
    x_(x)
    {
        
    }
    std::shared_ptr<X> x_;
    int n_;
};

struct X : std::enable_shared_from_this<X>
{
    void d()
    {
        auto y = make_shared<Y>(20, this->shared_from_this());
    }
    
};

int main()
{
    auto x = make_shared<X>();
    x->d();
}

CodePudding user response:

Use shared_from_this. Here you can find an example. This solution did not always work for me though so you have to try it out for your self. If it does not work use a raw pointer or a reference.

  • Related