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 warningdirective.#pragma warningallows selective modification of the behavior of compiler warning messages.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.
Or you can create a
#defineto workaround the warning.Some users stated that the code presented will not work because ScopeGuard is a typedef. This assumption is wrong.
http://www.ddj.com/cpp/184403758