开发者

const for non-reference arguments

If I have this code:

void Foo(aBasicType aI开发者_如何学Pythonn) //Where aBasicType is int, char etc.
{
    //...
}

Is there any point in making it const aBasicType since it is going to be copied anyway? One of the reasons I am asking is because I have seen it in 3rd party code and was wondering if there is something I am not aware of.


It cannot hurt to declare it const if you know that your function needs not modify its value during execution.

Note that functions that change their arguments, when arguments are passed by value, should be rare.

Declaring your variable const can prevent you from writing if (aIn = someValue).


I sometimes (infrequently) do it, when there is temptation to modify aIn in-place instead of making another copy, yet the method relies on aIn remaining unchanged throughout. It tends to be a close call though.


The reason is informative: you want the compiler to warn/error when a value-passed argument is seen on the left of an assignment. It's a bit cumbersome, seen on libs whose audience may be less than "well informed" on C or C++ (it's the same for both languages).


That would make the value const for that function, which might be useful in the same way declaring a constant at the top of your function might be useful.


No, adding const to a scalar call-by-value parameter is meaningless and will only be confusing.


I prefer to add const qualifier to input paramters regardless to parameter passing method (by value, by pointer or by reference). So const parameter simply means "input parameter" and non-const parameter means "output parameter" (or, rarely, inout parameter). I suppose such a convention makes code more understandable but it is matter of taste, of course.


I think I can formulate this much simpler. When footype is not a template parameter:

  • const footype & in the signature is a guarantee for the caller of the function and a constraint for the implementer of the function.

  • const footype on the other hand is only a constraint for the
    implementer and irrelevant to the caller.

When footype is a template parameter, then the rules can only be tested against the individual template instantiations.

BTW, if you see const constraints, then the connected code is much easier to read because the possibilities of what the code can do is much restricted. This is one of the many reasons why C++ is easier to read than C# or Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜