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

前端 未结 4 869
天涯浪人
天涯浪人 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条回答
  •  情歌与酒
    2020-11-28 08:44

    On the one hand you can use them to prevent functions that are semantically nonsensical to call on temporaries from being called, such as operator= or functions that mutate internal state and return void, by adding & as a reference qualifier.

    On the other hand you can use it for optimizations such as moving a member out of the object as a return value when you have an rvalue reference, for example a function getName could return either a std::string const& or std::string&& depending on the reference qualifier.

    Another use case might be operators and functions that return a reference to the original object such as Foo& operator+=(Foo&) which could be specialized to return an rvalue reference instead, making the result movable, which would again be an optimization.

    TL;DR: Use it to prevent incorrect usage of a function or for optimization.

提交回复
热议问题