英文:
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
后对象不再存在,所以我不确定为什么Interface
和Impl
中都不适用&&
。
英文:
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); }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论