1. 使用 nullptr,而不要使用 NULL 或 0 表示空指標。
考慮以下兩個 Func,傳入 0 時會呼叫 Func(int),而傳入 NULL 時會預期呼叫的是 Func(void*),可惜事與願違,呼叫的還是 Func(int),這是因為 NULL 被定義為 0,在 C++ 11 你只要改用 nullptr 就可以消除這種歧義。
void Func(void*){}
void Func(int){}
int main()
{
Func(0); // call Func(int)
Func(NULL); // call Func(int),不如預期
Func(nullptr); // call Func(void*)
return 0;
}
2. 使用 Raw string literals 取代逸出字元的使用。
以前要顯示 ” 或 之類的字元需要在前面加上 ,現在不用了,直接將字串用 R”(要顯示的字串)” 包起來即可。
int main()
{
const char* s1 = ""hellonworld"";
const char* s2 = R"("hellonworld")";
const char* s3 = R"("helloworld")";
std::cout << s1 << std::endl;
std::cout << std::endl;
std::cout << s2 << std::endl;
std::cout << std::endl;
std::cout << s3 << std::endl;
return 0;
}
3. 使用 Digit separators 增加程式碼可讀性。
如果程式碼內有一個很大的數字,現在可以使用 ‘ 來幫助閱讀,例如當作千分位使用。
int main()
{
unsigned long long n1 = 10929085235;
unsigned long long n2 = 10'929'085'235;
std::cout << n1 << std::endl;
std::cout << n2 << std::endl;
return 0;
}
留言
張貼留言