作者babyghost (Python语法真精简 Orz)
看板C_and_CPP
标题Re: [问题] 建构元初始化
时间Thu Feb 16 00:45:54 2006
※ 引述《justinC (无)》之铭言:
: 请问用串列初始化
: 跟 在建构元内写指定来初始化两个差异性在哪 各有啥好处
我听过的翻译是叫 "初始化串列" " initial list "
差在用 initial list 时, object 会呼叫 constructor 会比较快.
在 {} 里叫用 operator = 会比较慢一点, 你多呼叫了一个函式.
以下为例 :
class Student
{
public:
// version1 : use initial list.
Student( const string& str )
: name( str )
// just call copy constructor.
{}
// version2 : non-use initial list.
Student( const string& str )
{
// compiler 会偷偷插入 name::string()呼叫预设建构子初始化
name = str;
// call string::operator=.
}
string name;
};
note: version1 和 version2 不可能同时存在. (这里是example XD)
version1:
name 呼叫 class string 的建构子. <= 只呼叫一次.
version2:
compiler 会在建构子偷偷插入 name::string() 呼叫预设建构子.
接下来 name = str 会呼叫 class string 的 operator = (...).
=> 呼叫二次.
note:
若 string operator = 内部实作是用动态配置记忆体的话,
你还要先 delete 掉 buffer 再重新 allocate 够大的 buffer
然後再塞 data.
不管 operator = 实作再快, 都逃不了 compiler 偷偷塞的
预设建构子呼叫, 比 initial list 就是多了一次呼叫.
好处: (个人意见 XD)
initial list : 比较快.
一般写法 : 比较慢.
坏处:
initial list : 写时比较麻烦(其实也还好 )
一般写法 : 易读.
一般来说用 initial list 都比较快. 不过我想就一般基本型别应该没啥差
差的应该都是 user defined data.
: 我只知道用串列可以初始化const 的变数
嗯, 基本上
const type variable_name 的
都一定要用 initial list 初始化.
: 如果指定可以 配置动态记忆体
: 想问各个优缺点 谢谢
这个我完全看不懂你在写啥 XD
有错请指正 :)
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 210.192.143.24
1F:→ babyghost:写错,编译器偷塞的应该是 name.string::string(). 02/16 00:47
2F:→ babyghost:C++ Primer or efficient C++ Performance Programming 02/16 00:49
3F:→ babyghost:Techniques 的第五章 都可以参考一下 02/16 00:49
4F:推 justinC:好详细 我最後指的是 如果 char *字串 就要 allocate空间 02/16 01:06
5F:推 cplusplus:可以再加一点坏处 list无法事先作参数检查或额外处理 02/16 01:09
6F:→ cplusplus:另外如果是基本型别 两种效率相同 02/16 01:10
7F:→ cplusplus:list好处还有~ const成员的唯一初始化地方... 02/16 01:11
8F:推 godfat:我觉得参数检查应该放在外面说,放在里面像在测试 02/16 01:19
9F:→ cplusplus:没错误当然最好 可是使用者通常不会这麽乖orz 保险一点 02/16 01:23
10F:→ cplusplus:还是做错误检查比较好 可以做安全机制 02/16 01:24
11F:推 godfat:我的意思是在传给 c'tor 前先检查,不要放在 c'tor 内检查 02/16 01:27
12F:→ godfat:有的时候可以确定输入必为正确,放在 c'tor 内影响效率 02/16 01:27
13F:→ godfat:当然我想这还是要看情况就是了,没什麽绝对的 02/16 01:28
14F:推 UNARYvvv:member initialization list 02/16 19:31