[英]index operator constness
為什么我們需要兩個? 在哪種情況下會調用以下每個operator []?
class X {
public:
//...
int &operator [](int index);
const int &operator [](int index) const;
};
foo( X x )
{
x[0]; // non-const indexer is called
}
bar ( const X x )
{
x[0]; //const indexer is called
}
如果類X實例是const,則調用const版本,否則調用非const:
void function1( X& x )
{
x[0]; // x is non-const, non-const version is called
x[0] = ... // allright
}
void function2( const X& x )
{
x[0]; // x is const, const version is called
x[0] = ... // illegal - won't compile
}
這樣做是為了促進const正確性。
如果在const X對象上調用operator [],則將使用const; 否則為非常量。
X x;
x[42] = 42; // ok
X x_const;
x_const[42] = 42; // error: cannot assign to const reference
當類的實例稱為非常量類型時,將調用第一個。 當引用實例的類型為const時,調用第二個。
例如:
void check_array(X const& x)
{
// x[0] = 2; // That would be a compile error.
// And it's GOOD that we have such a check!
return x[1] == 5; //calls non-const version
}
void mutate_array(X& x)
{
x[0] = 2; // calls non-const version
if (x[1] == 5){ //calls non-const version anyway!
X const& const_ref = x;
return const_ref[1] == 5; //NOW it calls const version.
}
}
使用它的原因是:
check_array()
函數中) 使用2個版本為編譯器提供了優化的其他方式。 沒有值不能分配給const int&。 只要語句允許,就會調用第二個運算符,並且由於該運算符是const,因此編譯器還有其他優化的可能性。 只要將結果分配給該運算符的返回值,編譯器就會選擇第一個版本(不是const)。
有關更完整的說明,請參見Scott Meyers(更多)有效的C ++。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.