Re: [問題] reference 問題

看板C_and_CPP作者 (我要加入劍道社!)時間15年前 (2009/09/16 10:34), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串3/5 (看更多)
Sorry,這邊是我講錯啦~ 底下是破英文翻譯,加上我自己舉的例子。 The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except as specified below. 指向暫時物件的 reference,或是指向 subobject 所形成暫時物件的 reference, 其生命週期會與該 reference 的生命週期相同,除了下列的情況。 例: const string& s = string("hello"); 由 string("hello") 產生的暫時物件,生命週期和 s 相同。 A temporary bound to a reference member in a constructor’s ctor- initializer (12.6.2) persists until the constructor exits. 若物件擁有一個 reference 指向在建構式初始列中的暫時變數,該暫時變數會 保存到建構式結束。 例: class Obj { public: Obj(): s( string("hello") ) { cout << s << endl; // OK ... // 建構式結束後,s 指向的暫時物件將解構 } void print() { cout << s << endl; // 錯誤,暫時物件已不存在 } private: string& s; }; 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. 若函式的參數是指向暫時變數的 reference,該暫時變數會保存到整個包含函式 呼叫的運算式結束時。 例: int foo(string& s); void bar() { int i = foo( string("hello") ) + foo( string("world") ); } 暫時物件 string("hello") 和 string("world") 會在整個運算式 i = foo() + foo() 全部結束後才會解構。 A temporary bound to the returned value in a function return statement (6.6.3) persists until the function exits. 若 reference 指向函式的回傳物件,該暫時物件在離開函式後即銷毀。 例: string& foo(){ return string("hello"); // string("hello") 暫時物件在離開 foo() 後就會解構。 } string& s = foo(); // s 指向垃圾 至於後面大多在講暫時物件的解構順序是採取先進後出 (先建構的後解構)。 以上 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.29.108
文章代碼(AID): #1Ai4wiQO (C_and_CPP)
文章代碼(AID): #1Ai4wiQO (C_and_CPP)