Using UNREFERENCED_PARAMETER macro

2020-08-20 10:35发布

问题:

I'm using \W4 warning level on Visual Studio and I'm writing a Windows program.

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)

All these parameters are not used in my application, so I get warnings at compile time.

I know there are two ways of dealing with this:

  1. Commenting parameters HINSTANCE /*hInstance*/ ...
  2. Using the UNREFERENCED_PARAMETER macro

    int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
    {
      UNREFERENCED_PARAMETER(hInstance);
      UNREFERENCED_PARAMETER(hPrevInstance);
      UNREFERENCED_PARAMETER(lpCmdLine);
      UNREFERENCED_PARAMETER(nCmdShow);
    

Which one is the correct one? Which one is the safer to use? Are there any problems with using the macro?

回答1:

I would prefer commenting the parameters.

The macro UNREFERENCED_PARAMETER is defined in winnt.h and therefore not portable.

And if later you do reference it, you might overlook to remove the macro.

Edit: With C++17 you can now use the [[maybe_unused]] attribute. This is useful for code depending on preprocessor macros:

void foo( [[maybe_unused]] int value )
{
#ifdef USE_VALUE
   useValue(value);
#endif
}

Now there won't be warnings even if USE_VALUE is undefined.



回答2:

I consider the name-removing version the first to go with. It can have a disadvantage to confuse the information system so tooltip shows the crippled version. But healthy ones would use the declaration, where the names are there. (and for static and one-use things you should not have unused params, right?)

Otherwise it's matter of taste really.



回答3:

In C++, both are the correct ways to handle and do not introduce any unsafe-ness directly. However, the use of UNREFERENCED_PARAMETER can cause a maintenance issue because you need to remove the use of the macro if the parameter is used in the future updates, yet compilers do not warn that situation. To audit correct use of the macro, developers have to manually inspect that the parameters are still unused.

As others pointed out, cross-platform portability could be an issue too.

In C, it is not possible to remove the parameter name; hence the macro is the reasonable solution on the Windows platform, especially in Win32 programming.