资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

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

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

成都创新互联企业建站,十余年网站建设经验,专注于网站建设技术,精于网页设计,有多年建站和网站代运营经验,设计师为客户打造网络企业风格,提供周到的建站售前咨询和贴心的售后服务。对于成都网站建设、成都网站制作中不同领域进行深入了解和探索,创新互联在网站建设中充分了解客户行业的需求,以灵动的思维在网页中充分展现,通过对客户行业精准市场调研,为客户提供的解决方案。

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

Reason(原因)

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

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

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.

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

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

这是实现printf的基本方法。

Enforcement(实施建议)

  • Flag definitions of C-style variadic functions.

  • 标记定义了C风格可变参数函数的情况。

  • Flag #include  and #include

  • 标记代码中包含#include 和 #include 的情况。

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


名称栏目:C++中为什么不要定义C风格的可变参数函数
地址分享:http://cdkjz.cn/article/gcgpoj.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220