如何分配引用链的末端
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
权?
使用特殊的构造函数(并使用标记来区分构造函数和复制构造函数(:
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++ 字符串分配给另一个字符串
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- 为什么在将 are 值引用分配给时被视为 l 值引用?
- 将值分配给从函数返回的右值引用
- 取消引用 void 指针以将值分配给结构
- 将右值分配给左值引用
- 传入与在C++中分配常量引用
- 了解通过引用传递取消引用指针时C++堆/堆栈分配
- 可选参数常量引用重新分配
- 为什么在调用析构函数后仍然可以引用堆分配的对象
- 将非按引用变量分配给返回按引用的函数,反之亦然
- C++中右值引用的分配和不变性
- 如何在c++中引用动态分配的字符数组
- 当子对象引用被分配给父对象指针时,为什么不能访问子类
- C++取消引用未分配的内存,但没有分段错误
- shared_ptr和shared_array为引用计数器分配内存
- 将引用参数分配给局部变量
- 为什么常量引用在分配 l 值和 r 值时的行为不同