No, they cannot. The reasoning that they cannot because they are macros is silly. Macros are usable from constructors and destructors without any issues. However, va_start
and va_end
have specific requirements that they must be called from the same function. Moving them to separate functions is invalid. C++ refers to the C standard, and the C standard says "Each invocation of the va_start
and va_copy
macros shall be matched by a corresponding invocation of the va_end
macro in the same function." (7.15.1) If you do call va_end
from a helper class's destructor, it may work, or it may not. Since it doesn't meet the requirements of the standard, the behaviour is undefined.
Edit: as for the other question, do you need va_end
at all when an exception is thrown, a legitimate argument could be made that "invocation of the va_end
macro" doesn't actually require that the code reach the point where you invoke that macro (since macro invocation is strictly a compile-time-only action), but it strongly suggests that you do need it. So yes, use try
/catch
if exceptions are a possibility. The C99 rationale briefly notes in its description of va_copy
that va_start
may allocate memory. (I know of no implementation where it actually does do so.) On such an implementation, va_end
would then deallocate that memory, so skipping va_end
would cause a memory leak.
va_*
identifiers are macros.va_start()
you will have to useva_end()
inside the variadic function. Note that try-catch will significantly decrease performance if you plan on logging a lot.