const-correctness的定义是什么?

exc*_*ipy 5 c++ const

我认为"const-correctness"的概念定义得很明确,但当我与其他人谈论它时,似乎我们对它的含义有不同的看法.有人说它是关于在尽可能多的地方有"const"注释的程序.其他人将程序定义为const-correct,当且仅当使用const注释时没有违反constness(即,它是编译器为您检查的属性).

所以我想知道,这些函数中哪些是正确的:

struct Person {
    string getName1() const { return _name; }
    string getName2() { return _name; }
    string getName3() const { _name = "John"; return _name; }
    string getName4() { _name = "John"; return _name; }

    string _name;
};
Run Code Online (Sandbox Code Playgroud)

我在互联网上搜索了定义,但实际上找不到明确的答案,我也怀疑可能存在一个发生过中的柑橘生成案例.那么任何人都可以为定义提供任何可靠的引用吗?

Fle*_*exo 7

在我看来,"const正确性"意味着:

所有不打算修改的内容都应标记为const.

这意味着编译器可以在您出错时告诉您.(它也可能对某些条件下的优化产生影响,但这更多的是次要的好处,并取决于许多其他因素)

有三个基本的地方有用:

  1. 可以标记成员函数const,如示例中所示.这意味着您从该函数中访问成员变量就好像变量本身一样const.(这是你展示的例子,虽然getName3()不起作用)

  2. "自由"变量,本地变量和成员变量本身也可能被标记const- 一旦初始化,它们可能不会被更改.示例 - 局部变量:

    int f(int i) {
       const int square = i*i;
       // do something here that uses, but doesn't change square
       return square;
    }
    
    Run Code Online (Sandbox Code Playgroud)

    或自由变量:

    extern const double PI; // set somewhere else but not changed.
    
    Run Code Online (Sandbox Code Playgroud)

    或成员变量:

    class foo {
       const int state; // can't be changed once constructed
       foo(int s) : state(i) {}
    };
    
    Run Code Online (Sandbox Code Playgroud)
  3. 函数参数也可以标记const,定义仍然可以匹配非const声明:

    void f(int i);
    void f(const int i) {
        // the fact that i is const is an implementation detail of f here
    }
    
    Run Code Online (Sandbox Code Playgroud)

    作为附注const,在某些情况下需要引用的正确性:

    void g(const std::string& s);
    void f(std::string& s);
    
    Run Code Online (Sandbox Code Playgroud)

    在这两个中,可以在更多地方使用:

    g("hi"); // Fine
    f("hi"); // Not fine - you can't bind a temporary to a reference
    
    Run Code Online (Sandbox Code Playgroud)

    当然,如果你打算改变s那么通过一个临时的,无论如何都没有意义.