前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则ES.34:不要定义C风格的可变参数函数

C++核心准则ES.34:不要定义C风格的可变参数函数

作者头像
面向对象思考
发布2020-05-20 00:16:55
8570
发布2020-05-20 00:16:55
举报

ES.34: Don't define a (C-style) variadic function

ES.34:不要定义C风格的可变参数函数

Reason(原因)

Not type safe. Requires messy cast-and-macro-laden code to get working right.

这种方式不是类型安全的。需要繁杂的类型转换和宏装载代码来保证正确动作。

Example(示例)

代码语言:javascript
复制
#include <cstdarg>

// "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.

可选项:重载,模板,可变参数模板。

代码语言:javascript
复制
#include <iostream>

void error(int severity)
{
    std::cerr << '\n';
    std::exit(severity);
}

template <typename T, typename... Ts>
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.

这是实现printf的基本方法。

Enforcement(实施建议)

  • Flag definitions of C-style variadic functions.
  • 标记定义了C风格可变参数函数的情况。
  • Flag #include <cstdarg> and #include <stdarg.h>
  • 标记代码中包含#include <cstdarg> 和 #include <stdarg.h>的情况。

链接

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#-es34-dont-define-a-c-style-variadic-function

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-05-06,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • ES.34: Don't define a (C-style) variadic function
  • Reason(原因)
    • Note(注意)
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档