翻译《有关编程、重构及其他的终极问题?》——22.不要使用#pragram warning(default-X)

    xiaoxiao2021-03-25  105

    翻译《有关编程、重构及其他的终极问题?》——22.不要使用#pragma warning(default:X)

    标签(空格分隔): 翻译 技术 C/C++ 作者:Andrey Karpov 翻译者:顾笑群 - Rafael Gu 最后更新:2017年03月10日


    22.不要使用#pragma warning(default:X)

    下面的问题代码来自TortoiseGIT项目。PVS-Studio诊断的错误描述为:V665 Possibly, the usage of ‘#pragma warning(default: X)’ is incorrect in this context. The ‘#pragma warning(push/pop)’ should be used instead(译者注:大意是说在这里使用‘#pragma warning(default: X)’是不正确的,应该使用‘#pragma warning(push/pop)’)。

    #pragma warning(disable:4996) LONG result = regKey.QueryValue(buf, _T(""), &buf_size); #pragma warning(default:4996)

    解释 程序员经常以为在前面使用了“program warning(disable: X)”指令后,在使用“program warning(default: X)”指令后相关的警告就会重新恢复作用。但其实并非如此。“progma warning(default)”指令会把‘X’警告设置为默认状态,这其实并不是我们想要的(译者注:其实默认状态也许是disable的呢?)。

    假设我们在编译一个源文件时使用了/Wall开关,然后C4061警告就会产生,如果你增加了“#progma warning(default: 4061)”执行,这个警告就不会显示,因为默认就是被关掉的。

    正确的代码

    #pragma warning(push) #pragma warning(disable:4996) LONG result = regKey.QueryValue(buf, _T(""), &buf_size); #pragma warning(pop)

    建议 正确的回到关闭警告之前状态的方式是使用“#progma warning(push[,n])”和“#progma warning(pop)”。请看Visual C++关于这这些指令的描述文档:Progma Directive. Warnings。

    库的开发者一定要注意V664警告。不注意的警告处理可能会给库的使用者带来很多麻烦。

    这里推荐一篇关于这个话题的不错的文章:So, You Want to Suppress This Warning in Visual C++。

    转载请注明原文地址: https://ju.6miu.com/read-23916.html

    最新回复(0)