c++c++11c++14ref-qualifierfunction-qualifier

Is there any real use case for function's reference qualifiers?


Recently I learned about function's reference qualifiers, e.g.

struct foo
{
    void bar() {}
    void bar1() & {}
    void bar2() && {}
};

Where I might need this feature, is there any real use case for this language feature ?


Solution

  • There are basically two uses:

    1. To provide an optimized overload, for example to move a member out of a temporary object instead of having to copy it.
    2. Prevent misuse of an API. For example, no one would expect

      int a = 1 += 2;
      

      to work and this would also cause a compile error. However

      string b = string("foo") += "bar";
      

      is legal if operator += is declared as

      string & operator += (string const & o);
      

      as is usually the case. Also this has the nasty side-effect of providing an lvalue-reference to your rvalue. Bad idea. This can easily be prevented by declaring the operator as

      string & operator += (string const & o) &;