[英]C++ Constant return type of suffix increment operator
在C ++中,無論我在網上什么地方看到后綴增量運算符聲明的示例,都始終聲明為
T& operator++(int);
我相信這是后綴增加的正確語法,不是嗎?
問題是,每當我聲明后綴遞增時,我都使用const
關鍵字聲明返回類型,以便它變得類似於左值。
請參見示例代碼:
class AClass
{
int foo;
public:
AClass(void) : foo(0) {};
// Suffix increment operator
// Consider adding const to return type
/* const */ AClass operator++(int)
{
AClass cp(*this);
foo++;
return cp;
};
// Prefix increment operator
AClass& operator++()
{
foo++;
return *this;
};
};
int main(int argc, const char* args[])
{
/* This code would fail to compile.
int bar = 5;
(bar++)++;
*/
// Similarily, I would expect this to fail
// but it will succeed unless I use const return type.
AClass a;
(a++)++;
}
我從來沒有遇到過這種用const聲明的運算符的問題,而且我知道它已經保存了我們代碼的保存,該代碼由笨拙的同事制作。 因此,我的問題是:
非常感謝你的回答!
后綴增加將返回一個臨時而不是引用(這意味着您的第一個簽名是錯誤的):
T& operator++() // prefix
{
this->increment();
return *this;
}
T operator++(int) // suffix
{
// Almost always, you'll have this code:
T tmp(*this); ++(*this); return tmp;
}
有些人喜歡對后綴運算符的返回值進行const限定,以避免編寫諸如
(a++).modify_me();
不修改a
(它適用modify_me
到一個臨時對象)。 與...對比
(++a).modify_me();
遞增a
然后修改它。
就我個人而言,我認為沒有必要(因為您可能對modify_me
副作用modify_me
)。 此外,在C ++ 11中,您可能希望將所述臨時綁定到(非const)右值引用。 const限定后綴運算符的返回類型可禁用這種可能性。
我相信這是后綴增加的正確語法,不是嗎?
如果用“正確”來表示“慣例”,則否。 如果您嘗試創建類似於整數的后綴運算符的行為,則它應按值返回。
const T operator++(int);
這是因為它會創建一個副本,然后遞增,然后返回副本。 由於該副本是本地副本,因此您絕對不希望通過引用將其返回。
可以使用或保留的const,但是按值而不是引用的返回是必不可少的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.