What are “rvalue references for *this” for?

后端 未结 3 808
别那么骄傲
别那么骄傲 2020-12-05 02:56

What are the most typical use cases of \"rvalue references for *this\" which the standard also calls reference qualifiers for member functions?

By the way, there is

3条回答
  •  粉色の甜心
    2020-12-05 03:28

    Some operations can be more efficient when called on rvalues so overloading on the value category of *this allows the most efficient implementation to be used automatically e.g.

    struct Buffer
    {
      std::string m_data;
    public:
      std::string str() const& { return m_data; }        // copies data
      std::string str()&& { return std::move(m_data); }  // moves data
    };
    

    (This optimisation could be done for std::ostringstream, but hasn't been formally proposed AFAIK.)

    Some operations don't make sense to call on rvalues, so overloading on *this allows the rvalue form to be deleted:

    struct Foo
    {
      void mutate()&;
      void mutate()&& = delete;
    };
    

    I haven't actually needed to use this feature yet, but maybe I'll find more uses for it now that the two compilers I care about support it.

提交回复
热议问题