[Qt-creator] const-correctness and setter

Koehne Kai Kai.Koehne at digia.com
Fri Jun 6 09:31:08 CEST 2014


> -----Original Message-----
> From: qt-creator-bounces+kai.koehne=digia.com at qt-project.org [mailto:qt-
> [...]
> Why? If int would not be a POD, we would pass a const reference mainly to
> avoid the costs of passing by value. This, of course, is not necessary for an
> integer. The second aspect, however, is that we promise the caller, we wont
> change the argument, - which is also not needed if we pass the argument by
> value - but it also protects us from accidentally changing the argument's
> value. With setFoo(int foo) we forgo this aspect.

The argument is that you write the API for the 'outside', not the inside. And  for the
outside, const pass-by-value is just noise, and clutters the API. 

Some discussions on stackoverflow.com:

http://stackoverflow.com/questions/117293/use-of-const-for-function-parameters

A GotW about const-correctness:

http://www.gotw.ca/gotw/006.htm

"Normally const pass-by-value is unuseful and misleading at best."

> Additionally when we create a local variable in a function, we declare it const.
> Again, to protect us from accidentally changing it, but also that the compiler
> can put this variable into the read only section to gain speed/performance
> etc. Does that not also apply to an argument?

Either the method is inline. Then the compiler will look into the implementation, and
do any optimization possible, anyway. If it's not inline, the compiler has to put the value on the stack when calling, whether it's declared const, or not. So I very much doubt that having const pass-by-value arguments help the compiler in any way. 

Regards

Kai



More information about the Qt-creator mailing list