空引用 - C ++标准中的位置

时间:2011-04-08 01:40:02

标签: c++ pointers null reference standards

  

可能重复:
  C++: null reference
  When does invoking a member function on a null instance result in undefined behavior?

C ++标准中是否有任何部分显示NULL引用格式不正确? 我试图展示我的讲师(这是为了我正在评分的作业)以下表达式是未定义的行为:

AClass* ptr = 0;
AClass& ali = *ptr;
std::cout << "\n" << (AClass*) &ali << '\n';

我看到的违规是取消引用空指针,然后引用空引用。在他用作正确的示例的程序中,他正在比较取消引用的指针引用的返回值:

(AClass*) &ali != (AClass*) 0

作为对象有效性的测试。我认为这是完全未定义的行为;我想从标准中找到一个引用,这对我的解释更为具体。

如果我错了,请告诉我出错的地方。

2 个答案:

答案 0 :(得分:6)

§8.5.3/ 1:“声明为T&amp;的变量,即”对类型T的引用“(8.3.2),应由类型为T的对象或函数初始化,或者由可以转换为T的对象。“

上面的代码没有使用类型T的对象或函数或可以转换为T的对象初始化引用。违反了“shall”。此时,唯一的问题是它是否是未定义的行为,或者这是否符合可诊断规则,在这种情况下,编译器将需要提供错误消息。无论哪种方式,它显然是错误的。

答案 1 :(得分:0)

如果要重新分配,则应使用指针而不是引用。引用一劳永逸地初始化,不能重新分配。可以创建指针但保持未初始化,并且可以重新分配指针。

8.3.2 / 1:

A reference shall be initialized to refer to a valid object or function. 
[Note: in particular, 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. As described in 9.6, a reference cannot be bound directly to a bit-field]

1.9 / 4:

Certain other operations are described in this International Standard as undefined 
(for example, the effect of dereferencing the null pointer)