Can I declare a non-member function const in C++?

2019-02-03 13:39发布

问题:

Can I declare a non-member function (global function, may be) as const in C++? I understand that the const keyword actually is applied to the implicit "this" argument passed in member functions. Also since only member functions follow the "thiscall" calling convention, can const be applied for non-member functions?

Leaving aside what I am trying to do by declaring non-member function const, would compiler report error for doing so?

回答1:

No, only a non-static member function may be const qualified.

What semantic would you expect from a const non-member function ? If you want to enforce that no parameters are modified by the function, just take them by const reference.



回答2:

To answer your second question: an attempt to use the member function syntax for a non-member (i.e. void foo() const; ) is a grammar violation. Therefore, a compiler must give a diagnostic - either an error or a warning. It may not silently ignore the const. However, it may report a warning, then pretend the const wasn't there and produce an executable.