My program(C ) is defining a macro for throw
statements. It is something like:
#define FOO_THROW(some-exception-type, some-error-message) \
do \
{ \
[&]() __attribute__((cold, noinline)) \
{ \
using exception_type = some-exception-type; \
std::ostringstream ss; \
ss << some-error-message << ""; \
throw exception_type(ss.str()); \
} \
(); \
} \
while (0);
Then, it is getting called in the program, something like:
FOO_THROW(std::runtime_error, "error specfic message here")
I can see that we use do...while(0)
structure with the macro, what I want to understand is the use of lambda
and __attribute__
here, can someone explain that in simple words?
Basically, my focus is what is the need of lambda function here, when it can be done without it, is there can be any specific advantage of it here?
I am a beginner in C , so any hint in the right direction will do as well!
CodePudding user response:
do...while(0)
allows the macro to by called with semicolon at the end, i.e. macro(x,y,z);
(note the semicolon at the end), that's an old trick back from C, you can look it up separately.
As for the rest... it defines a lambda (immediate function object) capturing everything by reference (not sure why) that throws exception of a given type with a given message and calls it immediately, effectively throwing an exception.
The attributes signify the lambda is unlikely to be called (cold) and prevent from inlining (noinline), see: https://gcc.gnu.org/onlinedocs/gcc-4.7.2/gcc/Function-Attributes.html