如何调用成员的 rvalue 方法?

huangapple go评论55阅读模式
英文:

How to call rvalue methods of members?

问题

我正在编写一个类(Interface),它封装了一个类(Impl),该类恰好具有一个右值引用函数(参见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 给了我以下错误:

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

g++ 给了我以下错误:

main.cpp: 在成员函数‘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 { }
      |

我不太理解这个反馈。我明白在调用Close后对象不再存在,所以我不确定为什么InterfaceImpl中都不适用&&

英文:

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

得分: 5

_i 本身仍然是一个 lvalue,因此需要将其转换为 rvalue,以调用其 rvalue 限定的成员函数

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

_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); }

huangapple
  • 本文由 发表于 2023年7月17日 22:13:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76705338.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定