问题
I'm seeing a macro definition like this:
#define ASSERT_VALID_PARAM(param, assertion) { static_cast<void>(param); if (!(assertion)) { throw InvalidParamError(#param, #assertion, __FILE__, __PRETTY_FUNCTION__, __LINE__); } }
I'm not able to figure out the need of static_cast<void>(param)
here.
Any idea on why this is needed?
回答1:
This macro is designed to validate a certain real parameter passes a certain validation rule(s). The logic part of the macro is composed of 2 parts:
- Validate that
param
is a real parameter, with a valid name. This is done by using thestatic_cast
, and if an illegal name is used, a compile time error will be generated. - Validate the "truthyness" of
assertion
. This is done with a simple negating if statement.
If the param is a valid name, and the assertion fails (assertion == false
), an InvalidParamError
is thrown, using the passed in parameters as strings (using the Stringizing operator #) to initialize the error object.
Since the actual usage of the param
parameter in the macro is only as a string, it has to be validated using actual code. Since no real operation is needed the static_cast is used, which discards the result and can potentially be optimized out. Without that check, you could pass any value which would make the information in the assertion meaningless.
回答2:
it is the 'c++ way' of writing
(void)param;
it makes 'use' of the variable and thus disables the compiler warning for unused variable
回答3:
static_cast<void>(param);
will evaluate the param
and discard the result.
If you don't add the cast to void
:
- you may get warnings saying you are ignoring the result of expression.
- Even if you pass some illegal code (for example a statement instead of expression) as argument, compiler will accept it happily.
From cppreference
4) If new_type is the type void (possibly cv-qualified), static_cast discards the value of expression after evaluating it.
来源:https://stackoverflow.com/questions/30995131/what-is-the-use-of-static-castvoid-in-macro