What's a use case for overloading member functions on reference qualifiers?

前端 未结 4 862
天涯浪人
天涯浪人 2020-11-28 08:22

C++11 makes it possible to overload member functions based on reference qualifiers:

class Foo {
public:
  void f() &;   // for when *this is an lvalue
           


        
4条回答
  •  -上瘾入骨i
    2020-11-28 08:35

    One use case is to prohibit assignment to temporaries

     // can only be used with lvalues
     T& operator*=(T const& other) & { /* ... */ return *this; } 
    
     // not possible to do (a * b) = c;
     T operator*(T const& lhs, T const& rhs) { return lhs *= rhs; }
    

    whereas not using the reference qualifier would leave you the choice between two bads

           T operator*(T const& lhs, T const& rhs); // can be used on rvalues
     const T operator*(T const& lhs, T const& rhs); // inhibits move semantics
    

    The first choice allows move semantics, but acts differently on user-defined types than on builtins (doesn't do as the ints do). The second choice would stop the assigment but eliminate move semantics (possible performance hit for e.g. matrix multiplication).

    The links by @dyp in the comments also provide an extended discussion on using the other (&&) overload, which can be useful if you want to assign to (either lvalue or rvalue) references.

提交回复
热议问题