gpt4 book ai didi

c++ - 如何分配引用链的末端?

转载 作者:行者123 更新时间:2023-11-28 01:22:13 25 4
gpt4 key购买 nike

例如我有一个类:

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

如果对象是top,如何赋值father字段?我尝试了 Foo foo(foo);,但编译器警告我 foo 未初始化,我猜编译器只在所有初始化完成后才将内存分配给 foo 对象,所以如果我这样做, 父亲 将引用一些乱七八糟的内存地址。

那么,在这种情况下,如果对象是top,如何分配father呢?

最佳答案

使用一个特殊的构造函数(并使用一个标签来区分你的构造函数和 copy constructor ):

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

关于c++ - 如何分配引用链的末端?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55590121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com