确定 vsprintf 输出的大小

Determining size of vsprintf output

我正在为 class 实现一个类似于 printf(const char * format, ...) 的方法,我需要确定它的输出的确切大小,只给出提供的 formatva_list,在调用 vsprintf() 执行实际写入之前。

是否有函数可以使用 formatva_list 来生成输出的精确长度?

example in the documentation 开始,您可以确定必要的缓冲区大小 1st(强调我的):

std::vector<char> buf(1+std::vsnprintf(NULL, 0, fmt, args1)); // <<<
va_end(args1);
std::vsnprintf(buf.data(), buf.size(), fmt, args2);

4) Writes the results to a character string buffer. At most buf_size-1 characters are written. The resulting character string will be terminated with a null character, unless buf_size is zero. If buf_size is zero, nothing is written and buffer may be a null pointer, however the return value (number of bytes that would be written not including the null terminator) is still calculated and returned.

如果目标缓冲区参数作为 NULLnullptr.[=16= 传递,通常 <x>sprintf() 函数系列的所有变体都可用于计算必要的缓冲区大小]