C++: Operator= returns const reference of *this? | Chandler@Berlin

Chandler@Berlin

ベルリン在住

C++: Operator= returns const reference of *this or reference of *this?

Abstract

最近,cppcheck を使い始めた.私は operator= の返り値を *this の const reference にしていたのだが,cppcheck はこれを単なる reference にすべきだと指摘する.その理由を考えた.

Contents

cppcheck は C++ コードを静的に解析するツールである.(http://cppcheck.sourceforge.net/) メモリリークなどのエラーまである程度指摘するなどなかなかすごいツールである.このツールは,operator= が const のthis reference を返すと単なる reference を返すべきだと指摘する.以下にそのコードを示す.

---
#include
class OpTest {
public:
/// constructor
OpTest(int init_int) : m_int(init_int){
// empty
}
/// operator= with const reference
OpTest const & operator=(OpTest const & rhs){
if(this != &rhs){
m_int = rhs.m_int;
}
return *this;
}
public:
int m_int;
};
---

これを cppcheck に通すと,

---
[operator_substitute_00.cpp:9]: (style) 'OpTest::operator=' should return 'OpTest &'
---
と指摘される.

私は,インスタンスへの代入が終わったあとは, (*this) は const であるのが普通だと思っていたので,この指摘にはちょっと驚いた.それで Web を調べてみたのだが,この理由を説明している page はみつからなかった.ただ,多くのコードは const reference を返すよりも単なる reference を返している.

同僚の何人かに尋ねてみると,理由はあまり知られていないようだ.ただ,Aliが,代入の後に non const の method を実行できるからではないかと教えてくれた.つまり,

---
OpTest a(0);
OpTest b(1);
(a = b).non_const_method();
---

というような場合である.確かにそうかもしれない.ただ,私は個人的には

---
OpTest a(0);
OpTest b(1);
a = b;
a.non_const_method();
---
と書くだろうと思う.