首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >va_copy --移植到visual C++?

va_copy --移植到visual C++?
EN

Stack Overflow用户
提问于 2009-02-17 18:50:59
回答 4查看 13.9K关注 0票数 18

A previous question展示了打印到字符串的一种很好的方法。答案涉及到va_copy:

代码语言:javascript
复制
std::string format (const char *fmt, ...);
{
   va_list ap;
   va_start (ap, fmt);
   std::string buf = vformat (fmt, ap);
   va_end (ap);
   return buf;
}


std::string vformat (const char *fmt, va_list ap)
{
   // Allocate a buffer on the stack that's big enough for us almost
   // all the time.
   s ize_t size = 1024;
   char buf[size];

   // Try to vsnprintf into our buffer.
   va_list apcopy;
   va_copy (apcopy, ap);
   int needed = vsnprintf (&buf[0], size, fmt, ap);

   if (needed <= size) {
       // It fit fine the first time, we're done.
       return std::string (&buf[0]);
   } else {
       // vsnprintf reported that it wanted to write more characters
       // than we allotted.  So do a malloc of the right size and try again.
       // This doesn't happen very often if we chose our initial size
       // well.
       std::vector <char> buf;
       size = needed;
       buf.resize (size);
       needed = vsnprintf (&buf[0], size, fmt, apcopy);
       return std::string (&buf[0]);
   }

}

我遇到的问题是上面的代码不能移植到Visual C++,因为它不提供va_copy (甚至__va_copy)。那么,有谁知道如何安全地移植上面的代码呢?大概,我需要做一个va_copy拷贝,因为vsnprintf会破坏性地修改传递的va_list。

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/558223

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档