繁体   English   中英

循环引用:类没有构造函数,并且空成员shared_ptr值

[英]Circular reference: Class has no constructors and the null member shared_ptr value

我想这样做,但是有一个错误,说Y class has no constructors

class Y;
class X
{
    std::shared_ptr<Y> base;
    //other  private stuff
public:
    X()
    {
        base = std::shared_ptr<Y>(new Y(this));
    }
    std::shared_ptr<Y> Get(){ return base; }
};
class Y
{
    X d;
    //other private stuff
public:
    Y(X * b) :d(*b){}
};

用作

X x; // all values in X is defined
std::shared_ptr<Y> spy=x.Get();

spy包含X中的所有私有值,但其本身的shared_ptr为空。 这正常吗?

更多说明: spy包含d ,即X 如果在调试器中的spy内部查看d ,我会看到base为空。 我只有这个错吗?

由于X::X()的定义取决于特定Y构造函数的存在,因此需要在后者之后。 那是:

class Y;

class X
{
    std::shared_ptr<Y> base;
    //other  private stuff
public:
    X(); // just the declaration here, we don't know that Y(X*) is 
         // a valid constructor yet. 
    std::shared_ptr<Y> Get(){ return base; }
};

class Y
{
    /* all of Y */
};

// NOW, this is valid
// because we know that Y::Y(X*) is a valid constructor
X::X() {
    base = std::shared_ptr<Y>(new Y(this));
}

您的问题是, new Y(this)应该放置在完全定义Y的范围中,而不仅仅是声明。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM