如何分配引用链的末端

How to assign the end of a reference chain?

本文关键字:引用 何分配 分配      更新时间:2023-10-16

例如,我有一个类:

class Foo {
 public:
  Foo(const Foo& foo) : father(foo) {}
 private:
  const Foo& father;
};

如果对象是顶部,如何分配father字段?我尝试了Foo foo(foo);,但编译器警告我 foo 未初始化,我想编译器仅在所有初始化完成后才将内存分配给 foo 对象,所以如果我这样做,father将引用一些野生内存地址。

那么,在这种情况下,如果对象是顶部,如何分配father权?

使用特殊的构造函数(并使用标记来区分构造函数和复制构造函数(:

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