空引用 - 在 C++ 中的位置标准
C++ 标准中是否有任何部分表明 NULL 引用格式错误? 我试图向我的讲师(这是针对我正在评分的作业)表明以下表达式是未定义的行为:
AClass* ptr = 0;
AClass& ali = *ptr;
std::cout << "\n" << (AClass*) &ali << '\n';
我看到的违规行为是取消引用空指针,然后引用空引用。在他用作正确示例的程序中,他正在比较取消引用的指针引用的返回:
(AClass*) &ali != (AClass*) 0
作为对象有效性的测试。我认为这是完全未定义的行为;我想从标准中找到对我的解释更具体的引用。
如果我错了,请指出我哪里出错了。
Is there any section in the C++ standard the shows that NULL references are ill-formed?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
§8.5.3/1:“声明为 T& 的变量,即“对类型 T 的引用”(8.3.2),应由 T 类型的对象或函数或可以由被转换成T。”
上面的代码没有使用类型 T 的对象或函数或可以转换为 T 的对象来初始化引用。这违反了“应”。此时,唯一值得怀疑的地方是它是否是未定义的行为,或者这是否符合可诊断的规则,在这种情况下,编译器将需要给出错误消息。不管怎样,这显然是错误的。
§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."
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". 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.
如果您想重新分配,您应该使用指针,而不是引用。引用一劳永逸地初始化,并且不能重新分配。可以创建指针但未初始化,而且可以重新分配它们。
8.3.2/1:
1.9/4:
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:
1.9/4: