問題描述
如果我沒有真正訪問解引用的對象",解引用空指針是否仍然未定義?
If I don't actually access the dereferenced "object", is dereferencing the null pointer still undefined?
int* p = 0;
int& r = *p; // undefined?
int* q = &*p; // undefined?
一個稍微實際一點的例子:我可以取消引用空指針來區分重載嗎?
A slightly more practical example: can I dereference the null pointer to distinguish between overloads?
void foo(Bar&);
void foo(Baz&);
foo(*(Bar*)0); // undefined?
<小時>
好的,根據標準,參考示例肯定是未定義的行為:
Okay, the reference examples are definitely undefined behavior according to the standard:
在定義良好的程序中不能存在空引用,因為創建這種引用的唯一方法是將它綁定到通過取消引用空指針獲得的對象",這會導致未定義的行為強>.
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.
不幸的是,強調的部分是模棱兩可的.是 binding 部分導致了未定義的行為,還是 取消引用 部分就足夠了?
Unfortunately, the emphasized part is ambiguous. Is it the binding part that causes undefined behavior, or is the dereferencing part sufficient?
推薦答案
是的,它是未定義的行為,因為規范說左值指定一個對象或函數"(在第 3.10 條)并且它說 *
-操作符[解引用]的結果是一個左值,引用表達式指向的對象或函數"(見第 5.3.1 節).
Yes it is undefined behavior, because the spec says that an "lvalue designates an object or function" (at clause 3.10) and it says for the *
-operator "the result [of dereferencing] is an lvalue referring to the object or function to which the expression points" (at clause 5.3.1).
這意味著沒有描述取消引用空指針時會發生什么.這只是未定義的行為.
That means there is no description for what happens when you dereference a null pointer. It's simply undefined behavior.
這篇關于在什么時候取消引用空指針會變成未定義的行為?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!