Is it safe to use va_list in exception-prone code?

后端 未结 3 2370
生来不讨喜
生来不讨喜 2021-02-20 01:32

Typical example:

void foo(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);

    // might throw, might not.  who knows.
    bar(fmt, args);

            


        
3条回答
  •  不思量自难忘°
    2021-02-20 02:13

    The C++ standard defers this to the C standard.

    C99 (draft) 7.15.1/1 tells us that:

    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.

    Thus if bar throws, you fail to execute the va_end and your program has undefined behavior. If you add a try/catch to make sure that va_end is always called as required then you should be fine. But do remember that you can't pass non-PODs as varargs so if you need to handle them, you would need an alternate mechanism anyway.

    A more C++-like alternative would probably be insertion operators (operator<<) as is seen in the various iostreams provided by the language.

提交回复
热议问题