繁体   English   中英

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

[英]Null References - Where in the C++ Standard

可能重复:
C ++:空引用
什么时候在空实例上调用成员函数会导致未定义的行为?

C ++标准中是否有任何章节说明NULL引用格式错误? 我试图向我的讲师(这是我正在为其评分的作业)表明以下表达式是不确定的行为:

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

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

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

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

如果我错了,请显示我在哪里出错。

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

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM