使用#pragma warning push/pop 是暂时改变警告级别的正确方法吗?
有时很难编写完全不发出警告的 C++ 代码.然而,启用警告是一个好主意.因此,通常需要禁用围绕某些特定构造的警告,并在所有其他代码段中启用它们.
Once in a while it's difficult to write C++ code that wouldn't emit warnings at all. Having warnings enabled is however a good idea. So it is often necessary to disable warnings around some specific construct and have them enables in all other pieces of code.
到目前为止,我已经看到了两种方法.
I've seen two ways of doing that so far.
第一个是使用#pragma warning( push )
和#pragma warning( pop )
:
#pragma warning( push )
#pragma warning( disable: ThatWarning )
//code with ThatWarning here
#pragma warning( pop )
第二种是使用#pragma warning(default)
:
#pragma warning( disable: ThatWarning )
//code with ThatWarning here
#pragma warning( default: ThatWarning )
我在第二个变体中看到的问题是它丢弃了原始警告级别 - 警告可能在此之前已关闭,或者其警告级别可能已更改.使用 default
将丢弃这些更改.
The problem I see in the second variant is that it discards the original warning level - the warning might have been off before that or its warning level might have been altered. Using default
would discard those alterations.
第一种方法看起来很干净.它有什么问题吗?有没有更好的方法来实现相同的目标?
The first approach looks clean. Are there any problems with it? Are there any better ways to achieve the same?
推荐答案
第一种方法是最好的方法,IMO.我知道它没有问题.
The first method is the best way to do it, IMO. I know of no problems with it.
请记住,#pragma 是特定于编译器的,所以不要指望它适用于所有编译器:)
Simply bear in mind that a #pragma is compiler specific so don't expect it to work on every compiler out there :)
相关文章