你用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是没有意义的,因为你不会修改调用者的对象。

通过引用传递时应优先使用Const,除非函数的目的是修改传递的值。

最后,不修改当前对象(this)的函数可以,也可能应该声明为const。下面是一个例子:

int SomeClass::GetValue() const {return m_internalValue;}

这是一个不修改应用此调用的对象的承诺。换句话说,你可以调用:

const SomeClass* pSomeClass;
pSomeClass->GetValue();

如果函数不是const,则会导致编译器警告。

其他回答

If the parameter is passed by value (and is not a reference), usually there is not much difference whether the parameter is declared as const or not (unless it contains a reference member -- not a problem for built-in types). If the parameter is a reference or pointer, it is usually better to protect the referenced/pointed-to memory, not the pointer itself (I think you cannot make the reference itself const, not that it matters much as you cannot change the referee). It seems a good idea to protect everything you can as const. You can omit it without fear of making a mistake if the parameters are just PODs (including built-in types) and there is no chance of them changing further along the road (e.g. in your example the bool parameter).

I didn't know about the .h/.cpp file declaration difference, but it does make some sense. At the machine code level, nothing is "const", so if you declare a function (in the .h) as non-const, the code is the same as if you declare it as const (optimizations aside). However, it helps you to enlist the compiler that you will not change the value of the variable inside the implementation of the function (.ccp). It might come handy in the case when you're inheriting from an interface that allows change, but you don't need to change to parameter to achieve the required functionality.

你的例子中所有的const都没有目的。c++默认情况下是值传递的,因此该函数获得这些整型和布尔型的副本。即使函数修改了它们,调用者的副本也不会受到影响。

所以我会避免额外的const,因为

他们redudant 他们弄得乱七八糟 文本 他们阻止我 更改传入的值 它可能有用或有效的情况。

当参数按值传递时,Const是毫无意义的,因为你会 而不是修改调用者的对象。

错了。

它是关于自我记录你的代码和你的假设。

如果你的代码有很多人在工作,而且你的函数不是平凡的,那么你应该把const标记为任何你可以标记的东西。在编写工业级别的代码时,您应该始终假设您的同事都是精神病患者,他们试图以任何方式来对付您(特别是因为将来经常是您自己)。

此外,正如前面有人提到的,它可能会帮助编译器优化一些东西(尽管这是一个很长的机会)。

由于形参是按值传递的,从调用函数的角度来看,是否指定const没有任何区别。将按值传递的参数声明为const基本上没有任何意义。

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

int i = 5 ; // i is a constant

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