Const correctness: const char const * const GetName const (//stuff);

前端 未结 8 836
Happy的楠姐
Happy的楠姐 2020-12-19 08:48

Labelled as homework because this was a question on a midterm I wrote that I don\'t understand the answer to. I was asked to explain the purpose of each const in the follow

相关标签:
8条回答
  • 2020-12-19 09:28

    You have one more const than is syntactically allowed, that code would not compile. Remove the "const" after "char" and before the "*". Also, the last const must come before the function body. It helps to read things like this from right to left.

    const char * const GetName() const { return m_name; };
    

    You have a const function (i.e., the function does not alter the state of the class.), which returns a const pointer to a const char.

    0 讨论(0)
  • 2020-12-19 09:34

    Edit: Looks like I incorrectly pasted the code into Comeau, or it was edited in the original answer to be correct. In either case I'm preserving the answer below as if the code were incorrect.

    Comeau online compiler gives these results:

    "ComeauTest.c", line 4: error: type qualifier specified more than once
    const char const * const GetName() { return m_name; } const; ^

    "ComeauTest.c", line 4: warning: type qualifier on return type is meaningless const char const * const GetName() { return m_name; } const; ^

    "ComeauTest.c", line 4: error: declaration does not declare anything const char const * const GetName() { return m_name; } const;

    What this means is that your statement is malformed.

    const char const * const GetName() { return m_name; } const;
    

    The first and second consts mean the same thing. You can't specify the same qualifier more than once so one of these would have to be removed for the code to compile. Both of these consts specify that the values pointed to by the pointer returned by GetName cannot be modified, making code like this invalid:

    const char* name = c.GetName();
    name[0] = 'a';
    

    The third const specifies that the pointer returned by GetName() itself cannot be modified, but as Comeau points out, this doesn't accomplish anything on a return value because the return value is a copy of the pointer rather than the pointer itself, and can be assigned to a non-const pointer.

    The fourth const is misplaced, it should be between GetName and the function body like this:

    const char* GetName() const { return m.name; }
    

    This const specifies that no members of the class will be modified during the execution of GetName. Assuming that GetName a member of the class Person, this code would be allowed:

    const Person& p;
    p.GetName();
    

    Without this const, the above code would fail.

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