Is the const value parameter in definition but not declaration really C++?

前端 未结 7 1253
时光说笑
时光说笑 2021-01-06 13:31

This is similar to (but different from) this question.

Here is some simple test code to illustrate some weirdness I have discovered with Sun CC:

//--         


        
相关标签:
7条回答
  • 2021-01-06 14:02

    See C++ Coding Standards by Alexandrescu #15. This should work according to him. The const prevents the implementer of the function from changing the input variable. IMO the variable should remain const inside the function. If you need a variable, declare one. The optimizer will get rid of it for you.

    int temp = a;
    

    Since this does not work here I am advising my class to use the (const int a) in both the prototype and implementation. I am a big fan of using techniques that work for all compilers.

    0 讨论(0)
  • 2021-01-06 14:03

    This looks like a compiler problem in CC. The C++ standard says (in 13.1 Overloadable declarations):

    Parameter declarations that differ only in the presence or absence of const and/or volatile are equivalent. That is, the const and volatile type-specifiers for each parameter type are ignored when determining which function is being declared, defined, or called.

    But there are const/volatile modifiers that can participate in overloading, as the standard mentions shortly afterwards:

    Only the const and volatile type-specifiers at the outermost level of the parameter type specification are ignored in this fashion; const and volatile type-specifiers buried within a parameter type specification are significant and can be used to distinguish overloaded function declarations.

    0 讨论(0)
  • 2021-01-06 14:05

    My understanding is that this is allowed because it makes little difference for the caller. It is not the function that is const, but rather a parameter, and you are making the addition in the definition. Thus, the const you actually added affects only the implementation

    See this question.

    0 讨论(0)
  • 2021-01-06 14:08

    The const is void func1(const int) has no affect whatsoever on the function, since the int is passed by value --- a copy of the int is made, and that copy lives only as long as the function call. Whether or not you change that copy has no bearing on anything.

    You are probably confused by the fact that in void func2(const char*) the const is significant. But you have to recognized that is different from void func3(char* const). In the former, it's the character pointed to that cannot change; in the latter, it's the pointer that is (irrelevantly) 'const'

    0 讨论(0)
  • 2021-01-06 14:12

    Yes, a const int is not the same as an int.

    0 讨论(0)
  • 2021-01-06 14:15

    I would always match the const on both declaration and definition. This would reduce any problems because the signatures would match then.

    0 讨论(0)
提交回复
热议问题