[英]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.