在Effective C++第03项中,尽可能使用const.
class Bigint
{
int _data[MAXLEN];
//...
public:
int& operator[](const int index) { return _data[index]; }
const int operator[](const int index) const { return _data[index]; }
//...
};
Run Code Online (Sandbox Code Playgroud)
const int operator[]确实有所作为int& operator[].
但是关于:
int foo() { }
Run Code Online (Sandbox Code Playgroud)
和
const int foo() { }
Run Code Online (Sandbox Code Playgroud)
似乎他们是一样的.
我的问题是,为什么我们用const int operator[](const int index) const而不是int operator[](const int index) const?
最近我读过,从函数返回值来为非内置类型限定返回类型const是有意义的,例如:
const Result operation() {
//..do something..
return Result(..);
}
Run Code Online (Sandbox Code Playgroud)
我很难理解这个的好处,一旦对象被返回肯定是调用者的选择来决定返回的对象是否应该是const?
如果是这样,怎么样?这个问题甚至有意义吗?
在我的情况下,调用者修改返回的对象是没有意义的,所以我想将其标记为不可修改.