0

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;
}
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
Cameron121341
  • 260
  • 1
  • 9
  • 1
    Also, out of concern caused by the wording of the question: If you are under the impression that `shared_ptr<>` is the "default" pointer to use, you are very mistaken. –  Oct 20 '21 at 13:50
  • Does this answer your question? [std::shared\_ptr of this](https://stackoverflow.com/questions/11711034/stdshared-ptr-of-this) –  Oct 20 '21 at 14:04

2 Answers2

0

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();
}

Brady Dean
  • 3,378
  • 5
  • 24
  • 50
-1

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.

Gian Laager
  • 474
  • 4
  • 14
  • It is not optimal so I'd suggest using shared_from_this, in case shared_from_this does not work I would suggest just using a raw pointer. – Gian Laager Oct 20 '21 at 14:00