你用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)
这有什么原因吗?这对我来说有点不寻常。
下面两行在功能上是等价的:
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,但那是另一篇文章。
我知道这个问题“有点”过时了,但当我遇到它时,其他人可能也会在未来这样做... ...我仍然怀疑这个可怜的家伙会在这里列出我的评论:)
It seems to me that we are still too confined to C-style way of thinking. In the OOP paradigma we play around with objects, not types. Const object may be conceptually different from a non-const object, specifically in the sense of logical-const (in contrast to bitwise-const). Thus even if const correctness of function params is (perhaps) an over-carefulness in case of PODs it is not so in case of objects. If a function works with a const object it should say so. Consider the following code snippet
#include <iostream>
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class SharedBuffer {
private:
int fakeData;
int const & Get_(int i) const
{
std::cout << "Accessing buffer element" << std::endl;
return fakeData;
}
public:
int & operator[](int i)
{
Unique();
return const_cast<int &>(Get_(i));
}
int const & operator[](int i) const
{
return Get_(i);
}
void Unique()
{
std::cout << "Making buffer unique (expensive operation)" << std::endl;
}
};
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void NonConstF(SharedBuffer x)
{
x[0] = 1;
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void ConstF(const SharedBuffer x)
{
int q = x[0];
}
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main()
{
SharedBuffer x;
NonConstF(x);
std::cout << std::endl;
ConstF(x);
return 0;
}
附注:你可能会认为(const)引用在这里更合适,并提供相同的行为。嗯,对的。只是给出了与我在其他地方看到的不同的画面……