c++ - 如何在默认构造函数中初始化引用成员?

标签 c++ pointers reference

问题说明了一切。

如果我要实现默认构造函数,使用 const 指针成员会更好吗?

最佳答案

需要使用成员初始化列表:

struct foo
{
  const int& ref;
  foo() : ref(some_value()) { }
}

确保 some_value() 不会给你一个临时值。它的生命只会延长到构造函数结束:

A temporary bound to a reference member in a constructor’s ctor-initializer (12.6.2) persists until the constructor exits.

关于c++ - 如何在默认构造函数中初始化引用成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15094416/

相关文章:

c++ - 将 QPropertyAnimation 应用于 QRect

c++ - 对象在将其指针转换为基数后未调用好的方法

c - 在 C 语法中返回指向函数的指针

c++ - '从 int 到 int 的无效转换*'

php - 用于向 HTML 文档中的 .js 和 .css 引用添加版本号的正则表达式

c++ - GetShortPathNameW 返回文件扩展名。我希望它忽略 .exe

可变序列 : How to create similar code block for each argument/type? 的 C++ 模板和代码生成

c++ - 在 firebreath 插件上创建子可编辑文本框窗口

c++ - 从 STL 容器中删除元素时是否调用析构函数?

python - 如何通过引用传递变量?