I have this code inside a constructor of a class (not written by me) and it writes a variable arg list to a tmp file.
I wondered why this would be needed? The tmpfile is removed after this ctor goes out of scope and the var arg list sits inside the m_str vector.
Can someone suggest a better way of doing this without the use of a tmpfile?
DString(const char *fmt, ...)
{
DLog::Instance()->Log("Inside DString with ellipses");
va_list varptr;
va_start(varptr, fmt);
FILE *f = tmpfile();
if (f != NULL)
{
int n = ::vfprintf(f, fmt, varptr) + 1;
m_str.resize(n + 1);
::vsprintf(&m_str[0], fmt, varptr);
va_end(varptr);
}
else
DLog::Instance()->Log("[ERROR TMPFILE:] Unable to create TmpFile for request!");
}
This is C++ code: I think you may be trying to solve the wrong problem here.
The need for a temp file would go away completely if you consider using a C++-esque design instead of continuing to use the varargs. It may seem like a lot of work to convert all the calling sites to use a new mechanism, but varargs provide a wide variety of possibilities to mis-pass parameters leaving you open to insidious bugs, not to mention you can't pass non-POD types at all. I believe in the long (or even medium) term it will pay off in reliability, clarity, and ease of debugging.
Instead try to implement a C++-style streams interface that provides type safety and even the ability to disallow certain operations if needed.