A previous question mostró una buena manera de imprimir en una cadena. La respuesta implicada va_copy:va_copy - ¿portar a C++ visual?
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]);
}
}
El problema que estoy teniendo es que el código anterior no puerto a Visual C++, ya que no proporciona va_copy (o incluso __va_copy). Entonces, ¿alguien sabe cómo portar con seguridad el código anterior? Presumiblemente, necesito hacer una copia de va_copy porque vsnprintf modifica de forma destructiva la va_va_list pasada.
he implementado cosas similares en VC++ y nunca he necesitado usar 'va_copy()'. ¿Qué sucede cuando lo intentas sin usar la copia? –
Quién sabe ... Puede parecer que funciona. Incluso si lo hace, no significa que sea seguro. – user48956
Aparentemente va_copy() es una cosa C99. Para VC++, estará bien utilizando la lista va_ original más de una vez sin preocuparse por una copia. vsnprintf no intentará modificar la lista aprobada. –