使值传递的参数不变的重点是什么?

Iam*_*non 4 c++ const pass-by-value

这是一个更普遍的问题:const如果通过值传递函数参数,是否有任何意义?

在我正在研究的代码中,我看到了很多以下内容:

void some_function(const std::vector<double> some_vec);
Run Code Online (Sandbox Code Playgroud)

std::vector是按值传递的,那么接下来的是什么const呢?

就像我理解函数是否通过引用传递向量一样:

void some_function(const std::vector<double> &some_vec);
Run Code Online (Sandbox Code Playgroud)

但我认为const前者没有任何意义.

Bat*_*eba 5

特别是在处理数学代码时,它非常有用,因为它可以阻止错误的重构者更改作为函数参数传入的变量。例如,您不想搞乱pi的值(令人烦恼的是,它不是 C++ 标准的一部分),或者诸如万有引力常数之类的东西。

(过去我见过pi *= 2;代码是由一位物理学家编写的,他坚信pi应该是大多数人所拥有的两倍大。)

在函数声明和定义中使限定符匹配也很好(尽管语言本身并不坚持这一点)。

诚然我不怎么用它。

  • 我呃...不太愿意回答这个问题 (2认同)
  • @StoryTeller:哦,但你应该!普朗克常数呢? (2认同)
  • 我喜欢普朗克常数。我认为它比阿伏加德罗的数字更好;) (2认同)

Wal*_*ter 5

关键是你要阻止函数体改变值.函数参数只是函数体中的自动变量,您可能希望确保它保持在其输入值.考虑

int foo(int x)
{
    /* lots of code */
    some_other_func(x);  // may modify x
    /* even more code */
    return x+42;         // x may have been modified
}
Run Code Online (Sandbox Code Playgroud)

int foo(const int x)
{
    /* lots of code */
    some_other_func(x);  // will not compile if x is taken by non-const reference
    /* even more code */
    return x+42;         // x is guaranteed at its input value
}
Run Code Online (Sandbox Code Playgroud)

根据经验,声明一切const不应改变的东西.然后,如果您或某人意外地尝试更改此类变量,将导致编译时错误.

另请注意,const声明符在函数声明中没有效果,但仅在函数定义中有效,即以下内容完全正常(事实上建议):

struct bar
{
   int foo(int) const;
   /* more code */
};

int bar::foo(const int x) const // possibly in another compilation unit
{
   ...
}
Run Code Online (Sandbox Code Playgroud)