[英]How to assign the end of a reference chain?
例如我有一個課:
class Foo {
public:
Foo(const Foo& foo) : father(foo) {}
private:
const Foo& father;
};
如果對象是頂部,如何分配father
字段? 我嘗試了Foo foo(foo);
,但是編譯器警告我foo未初始化,我猜編譯器僅在完成所有初始化后才將內存分配給foo對象,因此,如果我這樣做, father
將引用一些野生內存地址。
那么,在這種情況下,如果對象是頂部,該如何分配father
權呢?
使用特殊的構造函數(並使用標簽將您的構造函數與copy構造函數區分開):
struct father_tag {};
class Foo {
public:
Foo(const Foo& foo, father_tag) : father(foo) {}
Foo() : father(*this) {}
private:
const Foo& father;
};
// usage:
Foo father;
Foo next(father, father_tag{});
或者您可以使用指針而不是引用,將其留在鏈末尾的nullptr
中。 然后,您可以檢查if (father)
是否在結尾處:
class Foo {
public:
Foo(Foo const* pfather) : m_pfather(pfather) {}
Foo() : m_pfather(nullptr) {}
private:
Foo const* m_pfather;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.