va_copy - 移植到VISUAL C ++? [英] va_copy -- porting to visual C++?

查看:109
本文介绍了va_copy - 移植到VISUAL C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<一个href=\"http://stackoverflow.com/questions/69738/c-how-to-get-fprintf-results-as-a-stdstring-w-o-sprintf#69911\">A previous问题显示印刷一个很好的方式为字符串。答案涉及va_copy:

A previous question showed a nice way of printing to a string. The answer involved va_copy:

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]);
   }

}

我遇到的问题是,上述code不端口到Visual C ++,因为它不提供va_copy(甚至__va_copy)。因此,没有人知道如何安全端口上面code? presumably,我需要做一个va_copy副本,因为vsnprintf破坏性修改通过va_list的。

The problem I'm having is that the above code doesn't port to Visual C++ because it doesn't provide va_copy (or even __va_copy). So, does anyone know how to safely port the above code? Presumably, I need to do a va_copy copy because vsnprintf destructively modifies the passed va_list.

推荐答案

您应该能够只是做了常规的分配就完事了:

You should be able to get away with just doing a regular assignment:

va_list apcopy = ap;

这是技术上不可移植和不确定的行为,但它会与大多数编译器与架构工作。在x86调用约定,的va_list 是公正的指针进栈,并安全地复制。

It's technically non-portable and undefined behavior, but it will work with most compilers and architectures. In the x86 calling convention, va_lists are just pointers into the stack and are safe to copy.

这篇关于va_copy - 移植到VISUAL C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆