簡體   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