Dealing With C++ "initialized But Not Referenced" Warning For Destruction Of Scope Helpers?

- 1 answer

In Visual Studio, I often use objects only for RAII purposes. For example:

ScopeGuard close_guard = MakeGuard( &close_file, file );

The whole purpose of close_guard is to make sure that the file will be close on function exit, it is not used anywhere else. However, Visual Studio gives me a warning that a "local variable is initialized but not referenced". I want to turn this warning off for this specific case.

How do you deal with this kind of situation? Visual Studio thinks that this object is useless, but this is wrong since it has a non-trivial destructor.

I wouldn't want to use a #pragma warning directive for this since it would turn off this warning even for legitimate reasons.



Method 1: Use the #pragma warning directive.

#pragma warning allows selective modification of the behavior of compiler warning messages.

#pragma warning( push )
#pragma warning( disable : 4705 ) // replace 4705 with warning number

ScopeGuard close_guard = MakeGuard( &close_file, file );

#pragma warning( pop )

This code saves the current warning state, then it disables the warning for a specific warning code and then restores the last saved warning state.

Method 2: Use a workaround like the following. Visual Studio will be happy and so will you. This workaround is used in many Microsoft samples and also in other projects.

ScopeGuard close_guard = MakeGuard( &close_file, file );

Or you can create a #define to workaround the warning.

ScopeGuard close_guard = MakeGuard( &close_file, file );

Some users stated that the code presented will not work because ScopeGuard is a typedef. This assumption is wrong.

According to the C++ Standard, a reference initialized with a temporary value makes that temporary value live for the lifetime of the reference itself.