你用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,这些形参是引用(或指针),只是[in]数据,不会被函数修改。意思是,使用引用的目的是避免复制数据,不允许更改传递的参数。

在你的例子中,将const放在布尔b形参上只是对实现施加了约束,对类的接口没有贡献(尽管通常建议不改变形参)。

的函数签名

void foo(int a);

and

void foo(const int a);

是一样的,这就解释了你的。c和。h

Asaf

其他回答

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.

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

int i = 5 ; // i is a constant

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

关于编译器优化:http://www.gotw.ca/gotw/081.htm

如果使用->*或。*操作符,这是必须的。

它会阻止你写出

void foo(Bar *p) { if (++p->*member > 0) { ... } }

我刚才差点就这么做了,但这可能不是你想要的结果。

我想说的是

void foo(Bar *p) { if (++(p->*member) > 0) { ... } }

如果我在Bar *和p之间放了一个const,编译器会告诉我。

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

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

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