【问题标题】:Pass an object with this to another object将带有 this 的对象传递给另一个对象
【发布时间】:2021-12-07 08:15:14
【问题描述】:

如果我有一个Y,它有一个指向X 的成员指针,我如何在X 中创建Y 的实例?

我想过像这样传递它:

#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;
}

【问题讨论】:

  • 另外,出于对问题措辞引起的关注:如果您认为shared_ptr&lt;&gt; 是“默认”使用的指针,那您就大错特错了。
  • 这能回答你的问题吗? std::shared_ptr of this

标签: c++ c++14 shared-ptr


【解决方案1】:

这是使用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();
}

【讨论】:

    【解决方案2】:

    使用shared_from_thisHere you can find an example. 这个解决方案并不总是对我有用,所以你必须自己尝试一下。如果它不起作用,请使用原始指针或引用。

    【讨论】:

    • 这不是最优的,所以我建议使用 shared_from_this,如果 shared_from_this 不起作用我建议只使用原始指针。
    猜你喜欢
    • 2015-09-15
    • 1970-01-01
    • 2023-03-24
    • 2019-05-02
    • 2014-09-02
    • 2021-09-23
    • 2012-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多