【发布时间】:2013-04-02 21:37:03
【问题描述】:
这是我写的一个busybox,用于使用gcc-4.8.1+中的新功能(我认为clang-2.9+也应该这样做),用于N2439('this'的引用限定符):
class Foo
{
public:
Foo(int i) : _M_i(i) { }
int bar() & { return _M_i /= 2; }
int bar() const & { return _M_i; }
int bar() && { return 2 * _M_i; }
private:
int _M_i = 42;
};
int
main()
{
Foo ph(333);
ph.bar();
const Foo ff(123);
ff.bar();
Foo(333).bar();
}
在阅读标准 8.3.5 时,我认为这三个 bar() 方法应该是可重载的。我得到一个链接器错误:
[ed@localhost ref_this]$ ../bin/bin/g++ -std=c++11 -o ref_this ref_this.cpp
/tmp/ccwPhzqr.s: Assembler messages:
/tmp/ccwPhzqr.s:73: Error: symbol `_ZN3Foo3barEv' is already defined
如果我注释掉int bar() const &,我将无法解析ff.bar();:
[ed@localhost ref_this]$ ../bin/bin/g++ -std=c++11 -o ref_this ref_this.cpp
ref_this.cpp: In function ‘int main()’:
ref_this.cpp:26:10: error: no matching function for call to ‘Foo::bar() const’
ff.bar();
^
ref_this.cpp:26:10: note: candidates are:
ref_this.cpp:11:7: note: int Foo::bar() &
int bar() & { return _M_i /= 2; }
^
ref_this.cpp:11:7: note: no known conversion for implicit ‘this’ parameter from ‘const Foo’ to ‘Foo&’
ref_this.cpp:13:7: note: int Foo::bar() &&
int bar() && { return 2 * _M_i; }
^
ref_this.cpp:13:7: note: no known conversion for implicit ‘this’ parameter from ‘const Foo’ to ‘Foo&&’
这是 gcc 错误还是标准的一部分?
我不在我的电脑上,但 clang 说什么?
【问题讨论】:
-
Shameless self-plug 对于那些不知道这是怎么一回事的人。
标签: c++ c++11 reference this rvalue