你用const能做到什么程度?你只是在必要的时候才把函数变成const,还是从头到尾到处都用它?例如,想象一个简单的变异子,它接受一个布尔参数:

void SetValue(const bool b) { my_val_ = b; }

这个const真的有用吗?就我个人而言,我选择广泛地使用它,包括参数,但在这种情况下,我想知道它是否值得?

我还惊讶地发现,你可以在函数声明中的形参中省略const,但可以在函数定义中包含它,例如:

. h文件

void func(int n, long l);

. cpp文件

void func(const int n, const long l)

这有什么原因吗?这对我来说有点不寻常。


当前回答

我说const你的值形参。

考虑这个bug函数:

bool isZero(int number)
{
  if (number = 0)  // whoops, should be number == 0
    return true;
  else
    return false;
}

如果number形参是const,编译器将停止并警告我们这个错误。

其他回答

确实没有理由将值形参设为“const”,因为函数只能修改变量的副本。

使用“const”的原因是如果你通过引用传递更大的东西(例如有很多成员的结构体),在这种情况下,它确保函数不能修改它;或者更确切地说,如果您试图以常规方式修改它,编译器将报错。它可以防止它被意外修改。

May be this wont be a valid argument. but if we increment the value of a const variable inside a function compiler will give us an error: "error: increment of read-only parameter". so that means we can use const key word as a way to prevent accidentally modifying our variables inside functions(which we are not supposed to/read-only). so if we accidentally did it at the compile time compiler will let us know that. this is specially important if you are not the only one who is working on this project.

下面两行在功能上是等价的:

int foo (int a);
int foo (const int a);

显然,如果用第二种方式定义,就不能在foo对象体中修改a,但从外部看没有区别。

const真正有用的地方是引用或指针形参:

int foo (const BigStruct &a);
int foo (const BigStruct *a);

这就是说,foo可以接受一个大的参数,也许是一个千兆字节大小的数据结构,而不需要复制它。同时,它也告诉调用者:“Foo不会*改变参数的内容。”传递const引用还允许编译器做出某些性能决定。

*:除非它抛弃了const-ness,但那是另一篇文章。

const应该是c++的默认值。 像这样:

int i = 5 ; // i is a constant

var int i = 5 ; // i is a real variable

只要可以,我就用const。参数的Const意味着它们不应该改变它们的值。这在通过引用传递时尤其有价值。Const for function声明该函数不应更改类成员。