作者scwg ( )
看板C_and_CPP
標題Re: [問題] pointer的reference(this pointer)
時間Tue Jul 2 19:36:00 2013
第一次拿 C++ standard 來回答問題,請多多指教 m(_ _)m
我覺得問題在
28 inner = new Inner(this);
配上
13 Inner(Foo* const& ptr)
首先根據 C++ standard 9.3.2 The this pointer
1 In the body of a non-static (9.3) member function, the keyword this
is
a prvalue expression whose value is the address of the
object for which the function is called. The type of this in a member
function of a class X is X*.
(prvalue 表示是 rvalue, 但不是 xvalue, 大致上表示不是 movable)
然後 8.5.3 (Initializers) References
5 A reference to type "cv1 T1" is initialized by an expression of type
"cv2 T2" as follows:
...
- Otherwise, the reference shall be an lvalue reference to a non-volatile
const type (i.e., cv1 shall be const), or
the reference shall be an
rvalue reference.
- If the initializer expression
- is an xvalue (but not a bit-field), class prvalue, array prvalue or
function lvalue and "cv1 T1" is reference-compatible with "cv2 T2",
or
- has a class type (i.e., T2 is a class type), where T1 is not
reference-related to T2, and can be implicitly converted to an
xvalue, class prvalue, or function lvalue of type "cv3 T3", where
"cv1 T1" is reference-compatible with "cv3 T3"
...
- Otherwise, a temporary of type "cv1 T1" is created and initialized
from the initializer expression using the rules for a non-reference
copy-initialization (8.5). The reference is then bound to the
temporary.
因為 this 是 pointer prvalue, 所以只能走最後一條, 產生 temporary.
而 temporary 的生命期離開 28 行後就結束了,
因此之後再用 Inner::outer 就又變成未定義行為了.
※ 引述《QQ29 (我愛阿蓉)》之銘言:
: 大家好...
: 遇到一個詭異的程式結果
: 我想了好久
: 跟我預期的完全不一樣
: 想請教各位
: 為啥會有這種問題
: 並且想問說 這種寫法是不是很危險
: 程式碼很短
: 平台是windows VC
: http://codepad.org/xK3IbjUI
: 我現在遇到一個case
: 我這段程式碼就是在模擬這問題
: 某個inner class有記錄 一個外面的pointer
: 然後拿這個pointer 一直使用
: 但是外面這pointer 會不定時被delete
: 我若是拿這pointer繼續操作 , 就會crash
: 於是我天真的想說
: 我乾脆inner class記錄外面pointer的reference(透過this)
: 肉眼compile感覺應該可以達到
: 變成說外面只要記得把pointer設定成null
: 我裡面只要遇到多判斷if null就do nothing...
: 結果就是出現一些我意料之外的情形
: 若是成功, outerInstance 這物件應該會變成null...
: 問題疑點都寫在註解...
: 麻煩各位跑跑看 到底我哪裡觀念有大瑕疵
: 謝謝
--
-----BEGIN GEEK CODE BLOCK-----
Version: 3.12
GCS/M d-(+) s:+ a- C++$ UL++B+ P++(++++) L+ E--@ W++ N? o? K? w(++)
!O M !V PS++(+++) PE++(+++) !Y PGP t+++ !5 !X R !tv b++ DI++ D+
G e+++>++++ h--* r y+
------END GEEK CODE BLOCK------
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 128.36.232.45
推 QQ29:明天仔細想下,不過若不用smart ptr, 就沒救了嗎 07/03 01:19
→ azureblaze:可以在outer上面掛個event 07/03 01:27
→ azureblaze:dtor被呼叫的時候通知所有需要他的物件 07/03 01:27
→ azureblaze:不過multi thread要自己做好保護 07/03 01:41
推 xatier:推簽名檔XDDD 07/05 20:31
→ scwg:XD 現在很少見了, 話說 r 該改成 r% 了 XD 07/05 22:15
→ sardine:我看了你的推文 但覺得這跟我後半段描述的方式沒有什麼差 11/21 02:55