Const正确性警告c ++ [英] Const correctness warnings c++

查看:352
本文介绍了Const正确性警告c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道任何警告,C ++编译器提供帮助强制const正确性?例如,有一个警告产生的任何C ++方法,包含一个非const参数,从来没有在方法内部修改是很好。我看到有一个gnu编译器警告称为-Wsuggest-attribute = const;然而,当我使用这个标志我得到一个错误,说它不被识别。任何想法为什么?

Does anyone know of any warnings that C++ compilers provide that help to enforce const correctness? For instance, it would be nice to have a warning produced by any C++ method that contains a non-const parameter that is never modified inside of the method. I see that there is a gnu compiler warning called -Wsuggest-attribute=const; however, when I use this flag I get an error saying that it is not recognized. Any ideas why?

推荐答案

我不认为这样的警告存在,主要是因为它是无用的。只是因为参数没有在调用内部修改,并不意味着它应该是 const 只是为了它。

I don't think such a warning exists, mostly because it would be useless. Just because a parameter is not modified inside the call, doesn't mean it should be made const just for the sake of it.

考虑 virtual 函数。也许基类的设计者虽然没有修改基类中的参数,但是想要将它留给扩展类,无论是否修改该参数。

Think of virtual functions. Perhaps the designer of the base class, although not modifying the parameter in the base class, wants to leave it up to an extending class whether or not to modify that parameter.

此外,考虑大型应用程序,其中修改接口或API或任何成本很多。您可能不需要现在修改参数,但打算在将来这样做。你现在不会使它 const ,并且强制一个完整的重建,并且可能会冒险的错误,当你删除 const

Also, think of large applications, where modifying interfaces or API's or whatever costs a lot. You might not need to modify the parameter now, but intend to do so in the future. You're not going to make it const now, and force a full rebuild and probably risk errors in the future when you remove the const.

这篇关于Const正确性警告c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆