C++核心準(zhǔn)則邊譯邊學(xué)-I.24 避免相同類型的無(wú)關(guān)參數(shù)相鄰

I.24: Avoid adjacent unrelated parameters of the same type(避免相同類型的無(wú)關(guān)參數(shù)相鄰)
Reason(原因)
Adjacent arguments of the same type are easily swapped by mistake.
相同類型的毗鄰參數(shù)很容易被弄反。
Example, bad(反面示例)
Consider(考慮下面的代碼):
void?copy_n(T*?p,?T*?q,?int?n);??//?copy?from?[p:p?+?n)?to?[q:q?+?n)This is a nasty variant of a K&R C-style interface. It is easy to reverse the "to" and "from" arguments.
這個(gè)K&R C風(fēng)格接口的危險(xiǎn)變種。它很容易弄反to和from兩參數(shù)。
譯者注:譯者注:K&R指《The C Programming Language》一書(shū)的作者Kernighan和Ritchie二人,K&R風(fēng)格指他們?cè)谠摃?shū)中書(shū)寫(xiě)代碼所使用的風(fēng)格。
Use const for the "from" argument:
為from參數(shù)使用const修飾。
void?copy_n(const?T*?p,?T*?q,?int?n);??//?copy?from?[p:p?+?n)?to?[q:q?+?n)譯者注:如果from緩沖區(qū)為const類型,弄反參數(shù)就會(huì)產(chǎn)生編譯錯(cuò)誤。
Exception(例外)
If the order of the parameters is not important, there is no problem:
如果參數(shù)的順序不重要,則沒(méi)有問(wèn)題:
int?max(int?a,?int?b);Alternative(可選做法)
Don't pass arrays as pointers, pass an object representing a range (e.g., a span):
不要以指針形式傳遞數(shù)組,傳遞一個(gè)·表現(xiàn)range的對(duì)象(例如span):
void?copy_n(span<const?T>?p,?span?q );??//?copy?from?p?to?qAlternative(可選做法)
Define a struct as the parameter type and name the fields for those parameters accordingly:
將參數(shù)類型定義一個(gè)結(jié)構(gòu)體并為并根據(jù)參數(shù)為字段命名:
struct SystemParams {string config_file;string output_path;seconds timeout;};void initialize(SystemParams p);
This tends to make invocations of this clear to future readers, as the parameters are often filled in by name at the call site.
由于參數(shù)通常被調(diào)用者根據(jù)名稱賦值,這樣做有助于將來(lái)的讀者更明確地調(diào)用該函數(shù)。
Enforcement(實(shí)施建議)
(Simple) Warn if two consecutive parameters share the same type.
(簡(jiǎn)單)如果有兩個(gè)連續(xù)的參數(shù)的類型相同,報(bào)警。
