C++メモ
コンパイルエラー
$ clang++ test.cpp test.cpp:18:6: error: non-const lvalue reference to type 'C' cannot bind to a temporary of type 'C' C &c = test(); ^ ~~~~~~ 1 error generated.
上のコンパイルエラーになるソース
#include <cstdio> class C { public: C() {} void hello() { puts("hello"); } }; C test() { return C(); } int main(int argc, char* argv[]) { C &c = test(); c.hello(); return 0; }
const参照に変更するとコンパイルできる。C::hello()
にもconstを付ける。
#include <cstdio> class C { public: C() {} void hello() const { puts("hello"); } }; C test() { return C(); } int main(int argc, char* argv[]) { const C &c = test(); c.hello(); return 0; }
また、右辺値参照に変更してもコンパイルできる。
#include <cstdio> class C { public: C() {} void hello() { puts("hello"); } }; C test() { return C(); } int main(int argc, char* argv[]) { C &&c = test(); c.hello(); return 0; }