温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C++中为什么不要定义C风格的可变参数函数

发布时间:2021-11-26 14:21:19 来源:亿速云 阅读:159 作者:iii 栏目:大数据

本篇内容主要讲解“C++中为什么不要定义C风格的可变参数函数”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“C++中为什么不要定义C风格的可变参数函数”吧!

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

Reason(原因)

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

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

Example(示例)

#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.

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

#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>的情况。

到此,相信大家对“C++中为什么不要定义C风格的可变参数函数”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++
AI