what is the use of “static_cast<void>” in macro?

偶尔善良 提交于 2019-12-19 10:58:10

问题


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:

  1. Validate that param is a real parameter, with a valid name. This is done by using the static_cast, and if an illegal name is used, a compile time error will be generated.
  2. 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:

  1. you may get warnings saying you are ignoring the result of expression.
  2. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!