Question

Here is a busybox I wrote to play with the new feature in gcc-4.8.1+ (I think clang-2.9+ should do this too) for N2439 (ref-qualifiers for '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();
}

It looks to me reading the standard 8.3.5 that the three bar() methods should be overloadable. I get a linker error though:

[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

If I comment out int bar() const & I am unable to resolve 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&&’

Is this a gcc bug or part of the standard?

I'm not on my computer with clang on it but what does clang say?

Was it helpful?

Solution

This feature is not supported by GCC up to version 4.8.0. It should be supported by GCC 4.8.1, which has not been officially released yet.

To the best of my knowledge, the only major compiler that supports reference qualifiers on member functions at the moment is Clang. As you can see from this example, your code compiles fine on Clang 3.2.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top