Const correctness warnings c++

末鹿安然 提交于 2019-12-03 22:21:58

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.

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.

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.

Careful, a const parameter like this one:

void myFunc(int const param);

does not belong to the interface. It belongs to the local scope of the function implementation. In fact, this function:

int inc(int const param) { return param+1; }

may be declared as

int inc(int param);

It is not a violation of the const correctness paradigm to claim the right to modify a variable but not actually do it.

If you are worried about const_cast you can either not use it in the first place or simply grep for it in your code base.

-Wsuggest-attribute=const

This analysis requires option

-fipa-pure-const

which is enabled by default at

-O 

and higher

No, unfortunately there are no such warnings. You just get errors if you try to change const declared parameters. This is because missing const declarations do not change the correctness of the code from the compilers point of view. But const correctness is important for the compiler to discover potential optimizations and it improves the readability of the code. It is a matter of professionalism. Especially when using references const correctness is a must. I often refer to this.
The compiler itself takes const correctness very serious when operators (assignement, conversion, ...) come into play. A missing const here and the compiler refuses to use the operator because it makes a big difference if the given parameter may possibly be modified or not.

I'm not aware of such warnings and I think they would be rather hard to implement in a compiler - that is, they would slow it down. Maybe some static analysis tools have such features (but I'm not aware of those either).

As per Wsuggest-attribute=const, that is a different thing. It will suggest to use a gcc-specific "function attribute const", which is, basically, a mathematical function, receiving only values (no pointers), not reading or changing any static/global state and returning only a value (no pointers). For further description, look here: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html#Common-Function-Attributes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!