C++核心準(zhǔn)則ES.34:不要定義C風(fēng)格的可變參數(shù)函數(shù)

ES.34: Don't define a (C-style) variadic function
ES.34:不要定義C風(fēng)格的可變參數(shù)函數(shù)
Reason(原因)
Not type safe. Requires messy cast-and-macro-laden code to get working right.
這種方式不是類(lèi)型安全的。需要繁雜的類(lèi)型轉(zhuǎn)換和宏裝載代碼來(lái)保證正確動(dòng)作。
Example(示例)
#include
// "severity" followed by a zero-terminated list of char*s; write the C-style strings to cerr
void error(int severity ...)
{
va_list ap; // a magic type for holding arguments
va_start(ap, severity); // arg startup: "severity" is the first argument of error()
for (;;) {
// treat the next var as a char*; no checking: a cast in disguise
char* p = va_arg(ap, char*);
if (!p) break;
cerr << p << ' ';
}
va_end(ap); // arg cleanup (don't forget this)
cerr << '\n';
if (severity) exit(severity);
}
void use()
{
error(7, "this", "is", "an", "error", nullptr);
error(7); // crash
error(7, "this", "is", "an", "error"); // crash
const char* is = "is";
string an = "an";
error(7, "this", "is", an, "error"); // crash
}
Alternative: Overloading. Templates. Variadic templates.
可選項(xiàng):重載,模板,可變參數(shù)模板。
#include
void error(int severity)
{
std::cerr << '\n';
std::exit(severity);
}
template
constexpr void error(int severity, T head, Ts... tail)
{
std::cerr << head;
error(severity, tail...);
}
void use()
{
error(7); // No crash!
error(5, "this", "is", "not", "an", "error"); // No crash!
std::string an = "an";
error(7, "this", "is", "not", an, "error"); // No crash!
error(5, "oh", "no", nullptr); // Compile error! No need for nullptr.
}Note(注意)
This is basically the way?printf?is implemented.
這是實(shí)現(xiàn)printf的基本方法。
Enforcement(實(shí)施建議)
Flag definitions of C-style variadic functions.
標(biāo)記定義了C風(fēng)格可變參數(shù)函數(shù)的情況。
Flag?#include
?and?#include 標(biāo)記代碼中包含#include
和?#include 的情況。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#-es34-dont-define-a-c-style-variadic-function
覺(jué)得本文有幫助?請(qǐng)分享給更多人。
關(guān)注微信公眾號(hào)【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_(kāi)發(fā),面向?qū)ο笏伎迹?/span>
