How to call rvalue methods of members?

112 Views Asked by At

I'm writing a class (Interface), which encapsulates a class (Impl) which happens to have an rvalue function (see Impl::Close).

class Impl
{
public:
    /// Called from Dtor.
    /// You can't reuse this after it has been closed
    /// Therefore && added so need temporary / rvalue ref.
    void Close(int why) && noexcept { /*...*/ }
};



class Interface
{
public:
    void Close(int why) && noexcept { _i.Close(why); }
private:
    Impl _i;
};

Lintian gives me:

error: 'this' argument to member function 'Close' is an lvalue, but function has rvalue ref-qualifier

g++ gives me:

main.cpp: In member function ‘void Interface::Close(int) &&’:
main.cpp:15:51: error: passing ‘Impl’ as ‘this’ argument discards qualifiers [-fpermissive]
   15 |     void Close(int why) && noexcept { _i.Close(why); }
      |                                                   ^
main.cpp:4:10: note:   in call to ‘void Impl::Close(int) &&’
    7 |     void Close(int why) && noexcept { }
      |         

I don't really understand this feedback. I get that the object doesn't really exist after calling Close so I'm not sure why the && doesn't make sense in both Interface and the Impl.

1

There are 1 best solutions below

1
康桓瑋 On BEST ANSWER

_i itself is still an lvalue, so it needs to be converted to an rvalue to call its rvalue-qualified member function

void Close(int why) && noexcept { std::move(_i).Close(why); }