作者QQ29 (我爱阿蓉)
看板C_and_CPP
标题Re: [问题] reference 问题
时间Wed Sep 16 11:54:33 2009
谢谢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
1F:推 kkc:不知道你讲的是不是就是RVO 09/16 17:22
2F:→ QQ29:RVO是甚麽呀@@ 有全名嘛 09/16 17:48
3F:推 kkc:return value optimization 09/16 19:03
4F:→ nickexe:return 暂时物件; 和先存到temp再return, 新的compiler 09/18 02:49
5F:→ nickexe:说, 一般都会被 RVO, 所以产生出来的 ASM 都会一样. 09/18 02:50
6F:→ nickexe:另外 const A& object = A(); 有个有趣的应用 09/18 02:52
7F:→ nickexe:可以去 trace Loki 的 ScopeGuard 的 code, 有用到这特性 09/18 02:54