我应该返回const对象吗? [英] Should I return const objects?
问题描述
在有效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]; }
// ...
};
const int operator []
从 int&
<$> c $ c> int foo(){}
和
const int foo(){}
看起来他们是一样的。
我的问题是,为什么我们使用 const int operator [](const int index)const
而不是
int operator [](const int index)const
?
忽略非类类型的返回类型的顶级cv-qualifiers。
这意味着即使你写:
int const foo();
返回类型为 int
。如果返回类型是一个引用,当然,
const
不再是顶级,区分:
int& operator [](int index);
和
int const& operator [](int index)const;
(注意,在函数声明中,如上所述,
任何顶级cv限定符也被忽略。)
该区别也与返回值相关类类型:如果
return T const
,那么调用者不能在
返回的值上调用非const函数,例如:
class Test
{
public:
void f
void g()const;
};
测试ff();
Test const gg();
ff()。f(); // legal
ff()。g(); // legal
gg()。f(); // **非法**
gg()。g(); // legal
In Effective C++
Item 03, Use const whenever possible.
class Bigint
{
int _data[MAXLEN];
//...
public:
int& operator[](const int index) { return _data[index]; }
const int operator[](const int index) const { return _data[index]; }
//...
};
const int operator[]
does make difference from int& operator[]
.
But what about:
int foo() { }
and
const int foo() { }
Seems like that they're the same.
My question is, why we use const int operator[](const int index) const
instead of int operator[](const int index) const
?
Top level cv-qualifiers on return types of non class type are ignored. Which means that even if you write:
int const foo();
The return type is int
. If the return type is a reference, of course,
the const
is no longer top level, and the distinction between:
int& operator[]( int index );
and
int const& operator[]( int index ) const;
is significant. (Note too that in function declarations, like the above, any top level cv-qualifiers are also ignored.)
The distinction is also relevant for return values of class type: if you
return T const
, then the caller cannot call non-const functions on the
returned value, e.g.:
class Test
{
public:
void f();
void g() const;
};
Test ff();
Test const gg();
ff().f(); // legal
ff().g(); // legal
gg().f(); // **illegal**
gg().g(); // legal
这篇关于我应该返回const对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!