Re: [問題] reference 問題

看板C_and_CPP作者 (我愛阿蓉)時間14年前 (2009/09/16 11:54), 編輯推噓2(205)
留言7則, 3人參與, 最新討論串4/5 (看更多)
謝謝l大的解釋但是還有一些地方不解 請教各位 ※ 引述《littleshan (我要加入劍道社!)》之銘言: : 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 相同。 那為什麼 或是有什麼必要性 必須要使用ref=temp ref這種寫法呢? 如果我寫 const string s("hello"); 效率 或是 差別在哪? 我只知道ref可以減少一次copy 但是建構還是需要 所以跟直接初始物件 感覺這兩者沒有差別?????請強者解惑 : 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 指向垃圾 這邊想請教各位是 我實際去測試一下 如果foo的return type是回傳copy 也就是少加了& 他就不會馬上跳出foo就將他解構 這和上面講的const string& s = string("hello"); 是同樣道理嘛??? 最後就是~常常看到很多code很喜歡直接寫 return 暫時物件; 這和我先寫 物件 temp(初始); return temp; 這哪種是好習慣?? 效率上我也是覺得沒有差@@ 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.113.207.187

09/16 17:22, , 1F
不知道你講的是不是就是RVO
09/16 17:22, 1F

09/16 17:48, , 2F
RVO是甚麼呀@@ 有全名嘛
09/16 17:48, 2F

09/16 19:03, , 3F
return value optimization
09/16 19:03, 3F

09/18 02:49, , 4F
return 暫時物件; 和先存到temp再return, 新的compiler
09/18 02:49, 4F

09/18 02:50, , 5F
說, 一般都會被 RVO, 所以產生出來的 ASM 都會一樣.
09/18 02:50, 5F

09/18 02:52, , 6F
另外 const A& object = A(); 有個有趣的應用
09/18 02:52, 6F

09/18 02:54, , 7F
可以去 trace Loki 的 ScopeGuard 的 code, 有用到這特性
09/18 02:54, 7F
文章代碼(AID): #1Ai65wQF (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1Ai65wQF (C_and_CPP)