int() = 0

顯式的使用 int() 會回傳0
int a = int(); //a=0
這個在語法上看起來「像」是constructor,而效果上也很「像」constructor (default value = 0)

那麼這個語法的值是怎麼被決定的呢?
參考c++03

5.2.3 Explicit type conversion (functional notation)
 的第二點
 The expression T(), where T is a simple-type-specifier (7.1.5.2) for a non-array complete object type or
 the (possibly cv-qualified) void type, creates an rvalue of the specified type, which is value-initialized
 int是 simple-type-specifier
 那麼 什麼是value-initialized?
 參考 8.5 Initializers
 第五點
 To value-initialize an object of type T means
 ...
 — otherwise, the object is zero-initialized (int對應這條)
 
 To zero-initialize an object of type T means
 if T is a scalar type (3.9), the object is set to the value of 0 (zero) converted to T; (int對應這條)
 ... 

在使用上配合template T()會有一致性,跟void()有異曲同工之妙
事實上這樣在使用STL 如map, vector時不用擔心primitive type的初始值

例如

std::map<char, int=""> x;
 x['a']++; //這樣子最後會是1
//也就不需要像下面這樣寫
if(x.find('a') == x.end())
{
  x['a'] = 1;
}
else
{
 x['a']++;
}
This entry was posted in C++ Language. Bookmark the permalink.

Leave a Reply