Re: [問題] const reference

看板C_and_CPP作者 (阿貓)時間12年前 (2012/01/06 05:14), 編輯推噓3(300)
留言3則, 3人參與, 最新討論串3/3 (看更多)
※ 引述《Arton0306 (Ar藤)》之銘言: : 因為程式碼比較短也直接貼在下方(http://codepad.org/o7M1WcFG) : 程式碼輸出為 : 500 : 0 : 0 : 500 : 500 : 500 : 123 : 123 : 123 : 請問為什麼 int const & x 以 500 初始化後 此值會被洗掉 : 而 static int const &k = 123 這個值不會被洗掉 : 這背後的機制是什麼呢? : =========================================================== : #include <iostream> : #include <cstdio> : using namespace std; : class foo : { : public: : int const & x; : foo():x(500) : { : } : }; : void test2() : { : static int const &k = 123; : cout<<k<<endl; : } : int main() : { : foo a; : cout<<a.x<<endl; : cout<<a.x<<endl; : cout<<a.x<<endl; : const int &cir = 500; : cout<<cir<<endl; : cout<<cir<<endl; : cout<<cir<<endl; : test2(); : test2(); : test2(); : return 0; : } Background: const reference可以用來延長暫時物件的壽命: int f() { return 42; } { const int& x = f(); // The temporary int is bound to x. assert(x == 42); } // The temporary int returned from f() is actually destroyed here! ---- 但是有一些例外,參見C++ Standard §12.2.5 [class.temporary]: The temporary to which the reference is bound or the temporary that is the complete object to a subobject of which the temporary is bound persists for the lifetime of the reference except as specified below. A temporary bound to a reference member in a constructor's ctor-initializer (12.6.2) persists until the constructor exits. A temporary bound to a reference parameter in a function call (5.2.2) persists until the completion of the full expression containing the call. class foo { public: foo() : x(42) { } // The temporary int 42 is destroyed here!!! const int& x; }; { foo f; // f.x is a dangling reference here now. } ---- void f() { static const int& x = 42; } 這裡因為x的lifetime其實是從第一次呼叫f到程式結束, 所以這個暫時物件也會被延長到程式結束,可以安心使用 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.252.42

01/06 10:04, , 1F
好詳細的解答 感謝!
01/06 10:04, 1F

01/06 17:40, , 2F
推推推
01/06 17:40, 2F

01/06 20:28, , 3F
大神學長推!
01/06 20:28, 3F
文章代碼(AID): #1F1XAtpQ (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1F1XAtpQ (C_and_CPP)