c++ - va_copy -- 移植到 Visual C++?

标签 c++ c visual-studio-2008 visual-c++

A previous question展示了一种打印到字符串的好方法。答案涉及 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]);
   }

}

我遇到的问题是上面的代码没有移植到 Visual C++,因为它不提供 va_copy(甚至 __va_copy)。那么,有谁知道如何安全地移植上述代码?据推测,我需要做一个 va_copy 复制,因为 vsnprintf 破坏性地修改了传递的 va_list。

最佳答案

你应该能够摆脱只做一个常规的任务:

va_list apcopy = ap;

它在技术上是不可移植和未定义的行为,但它适用于大多数编译器和架构。在 x86 调用约定中,va_list 只是指向堆栈的指针,可以安全复制。

关于c++ - va_copy -- 移植到 Visual C++?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/558223/

相关文章:

c++ - 如何删除带有指向其他对象的指针的动态对象数组 (C++)

c - 对结构的写入无效

c - FFT 频率区间和 PIC32

c - 如何解决 fatal error LNK1000 : Internal error during IncrBuildImage?

c++ - 以非管理员身份在 Windows 上检查 C 中的上次文件修改时间

c++ - 传递派生类指针 C++ 时的运行时错误

c++ - 在 C++ 中每次都返回 false

c - 静态填充一个巨大的结构

c++ - 应用程序退出时线程无法退出 - C++

python - 找不到 vcvarsall.bat 文件