c++ - 在 C++ 中初始化对成员的引用为 NULL

标签 c++ reference initialization-list

是否可以在c++中将引用成员初始化为NULL?
我正在尝试这样的事情:

class BigClass
{
private:
  Object m_inner;
public:
  const Object& ReadOnly;
  BigClass() : ReadOnly(NULL)
  {
    Do stuff.
  }
};

我知道如果我将“ReadOnly”初始化为一个对象的真实引用,我可以做到这一点,但是当我想在那里输入“NULL”时,我得到了错误:

"cannot convert from 'int' to 'const Object &'

我该如何解决这个问题?

最佳答案

不,C++ 中的引用不能为 NULL1

可能的解决方案包括:

  • 使用指针而不是引用。
  • 有一个虚拟的 Object 实例,可以用来表示“没有对象”。

[1] 来自 C++11 standard :

[dcl.ref] [...] a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior.

关于c++ - 在 C++ 中初始化对成员的引用为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9055778/

相关文章:

Python:短坐标函数意外更改传入参数值

c++ - 初始化列表需要其效果的初始化函数调用?

c++ - 如何捕获初始化列表中的异常?

java - Java 和 C++ 之间是否有消息传递服务,例如 JMS for Java to Java?

c++ - 我想访问 std::unique_ptr 中的特定元素

c++ - 如何在不使用 variable_name.at() 的情况下引用字符串的最后一个字符?

c++ - 类型 ** 的包装器的数组订阅运算符的返回类型是 *&?

c++ - 在构造函数初始化列表中初始化成员数组(C++11 之前)

c++ - 如何创建 const boost::iterator_range

c++ - C 中的全局变量不连续