Why is const-correctness specific to C++?

后端 未结 14 519
盖世英雄少女心
盖世英雄少女心 2020-12-23 16:42

Disclaimer: I am aware that there are two questions about the usefulness of const-correctness, however, none discussed how const-correctness is necessary in C++ as oppos

14条回答
  •  礼貌的吻别
    2020-12-23 17:19

    For example you have a funcion:

    void const_print(const char* str)
    {
        cout << str << endl;
    }
    

    Another method

    void print(char* str)
    {
        cout << str << endl;
    }
    

    In main:

    int main(int argc, char **argv)
    {
        const_print("Hello");
        print("Hello");        // syntax error
    }
    

    This because "hello" is a const char pointer, the (C-style) string is put in read only memory. But it's useful overall when the programmer knows that the value will not be changed.So to get a compiler error instead of a segmentation fault. Like in non-wanted assignments:

    const int a;
    int b;
    if(a=b) {;} //for mistake
    

    Since the left operand is a const int.

提交回复
热议问题