简体   繁体   English

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

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

Possible Duplicates: 可能重复:
C++: null reference C ++:空引用
When does invoking a member function on a null instance result in undefined behavior? 什么时候在空实例上调用成员函数会导致未定义的行为?

Is there any section in the C++ standard the shows that NULL references are ill-formed? C ++标准中是否有任何章节说明NULL引用格式错误? I am trying to show my lecturer (this is for an assignment for which I am being graded) that the following expression is undefined behaviour: 我试图向我的讲师(这是我正在为其评分的作业)表明以下表达式是不确定的行为:

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

The violations I see, is dereferencing of a null pointer, and then referencing a null reference. 我看到的违规是取消引用空指针,然后再引用空引用。 In an a program he is using as a correct example, he is comparing the return of the dereferenced pointer reference: 在一个他用作正确示例的程序中,他正在比较已取消引用的指针引用的返回:

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

As a test for an objects validity. 作为对象有效性的测试。 I saw this as completely undefined behavior; 我认为这是完全未定义的行为。 I want to find a quote from the standard that is a bit more concrete for my explanation. 我想从该标准中找到一个报价,该报价对我的解释更为具体。

If I'm wrong, then please show where I have made an error. 如果我错了,请显示我在哪里出错。

§8.5.3/1: "A variable declared to be a T&, that is “reference to type T” (8.3.2), shall be initialized by an object, or function, of type T or by an object that can be converted into a T." 第8.5.3 / 1条:“声明为T&的变量,即“对T类型的引用”(8.3.2),应由T类型的对象或函数或可以为T的对象初始化。转换为T。”

The code above does not initialize the reference with an object or function of type T or an object that can be converted to T. The violates the "shall". 上面的代码未使用类型为T的对象或函数或可以转换为T的对象来初始化引用。违反了“应”。 At that point, the only room for question is whether it's undefined behavior, or whether this qualifies as a diagnosable rule, in which case the compiler would be required to give an error message. 那时,唯一的问题是它是否是未定义的行为,或者这是否符合可诊断的规则,在这种情况下,将要求编译器给出错误消息。 Either way, it's clearly wrong though. 无论哪种方式,这显然都是错误的。

You should use pointers, and not references, if you wish to reassign. 如果要重新分配,则应使用指针,而不是引用。 References are initialized once and for all and cannot be reassigned. 引用将一劳永逸地初始化,并且无法重新分配。 Pointers can be created but left uninitialized, plus they can be reassigned. 可以创建指针,但不要初始化指针,并且可以重新分配指针。

8.3.2/1: 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: 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