[問題] C++ FQA 文章中,有關 dangling refere …

看板C_and_CPP (C/C++)作者 (洞房不敗)時間16年前 (2009/02/23 19:44), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串1/3 (看更多)
大家好 在 google 連到這一系列的文章,叫 C++ FQA Lite,網址: http://yosefk.com/c++fqa/ 大概看了一下,似乎是對 C++ FAQ Lite 的內容有些不同的看法,所寫出來的文章 其中這篇講到 C++ References - [8.1] What is a reference? http://yosefk.com/c++fqa/ref.html#fqa-8.1 這段主要在反駁「reference 只是某物件的別名 (alias)」這件事 其中講到 dangling references 做例子,我不太能理解,有沒有前輩能舉例解釋一二? 節錄部份如下: ------------------------------------------------------------------------------ For example, a wide class of bugs comes from accessing dangling references - references to objects which were already destroyed. If a reference is the object, or just another name for it, how can that happen? ------------------------------------------------------------------------------ 我知道 dangling pointer 的意思以及怎樣才會發生。 但上面說的這個 dangling reference 導致的 bug 要怎樣才能重現我無法理解。 因為比如 main{ { int nobj = 1; int &nref = nobj; } /* 到這裡 nobj 已經消滅,可是 nref 也消滅了。reference 又不能像指標 一樣,晚點再決定參考誰,比如VC編譯器就會反應"沒有初始化" (error c2530) 那怎麼 dangling 呢? */ } 謝謝大家。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 124.8.147.85 ※ 編輯: zlw 來自: 124.8.147.85 (02/23 19:45)

02/23 21:04, , 1F
int& foo() {int x; return x;}
02/23 21:04, 1F
文章代碼(AID): #19eem3G_ (C_and_CPP)
文章代碼(AID): #19eem3G_ (C_and_CPP)