gpt4 book ai didi

c++ - 在临时对象上调用 lvalue-ref 限定成员函数时 GCC 错误消息的措辞

转载 作者:行者123 更新时间:2023-12-03 07:22:29 25 4
gpt4 key购买 nike

预期以下代码无法编译:

struct A {
void doWork() & {}
};
int main() {
A{}.doWork();
}
我的理解是临时的 A{}无法绑定(bind)到 & -限定成员函数 doWork ,这似乎与 cppreference 的摘录一致(我的斜体):

[…] member function of class X is treated as follows:

  • no ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X and is additionally allowed to bind rvalue implied object argument
  • lvalue ref-qualifier: the implicit object parameter has type lvalue reference to cv-qualified X and is not allowed to bind rvalue implied object argument
  • rvalue ref-qualifier: the implicit object parameter has type rvalue reference to cv-qualified X

还有 clangd我在 Vim 中使用的告诉我

'this' argument to member function 'doWork' is an rvalue, but function has non-const lvalue ref-qualifier deleteme.cpp:2:10: note: 'doWork' declared here [member_function_call_bad_ref]


但是,当我使用 GCC 进行编译时,会出现以下错误:
$ g++ -std=c++17 deleteme.cpp && ./a.out
deleteme.cpp: In function ‘int main()’:
deleteme.cpp:16:16: error: passing ‘A’ as ‘this’ argument discards qualifiers [-fpermissive]
16 | A{}.doWork();
| ^
deleteme.cpp:5:10: note: in call to ‘void A::doWork() &’
5 | void doWork() & {
| ^~~~~~
这似乎不像 clangd 中的错误那样与错误相关.
另一方面,当错误地调用 non- const member function on const object 时,我读过这两个词,丢弃限定符。 ;在这种情况下,我理解“丢弃”的使用,因为该对象具有 const该功能无法兑现,因此应该将其丢弃以使其正常工作。
但是,上面的代码似乎并非如此,据我了解,问题在于 A{} 的右值性与 doWork() & 的左值相比预计。
来自 GCC 的错误的措辞是错误的还是我误读了它?

最佳答案

这只是 GCC 中措辞欠佳的错误消息的一个例子。
我的猜测是,在 GCC 的实现中,诊断不同 ref-qualifiers 之间的不匹配与诊断 const 和 non-const 之间的不匹配共享一些代码,并且它们重用了相同的错误消息。
我会鼓励你 file a GCC bug建议改进错误消息。

关于c++ - 在临时对象上调用 lvalue-ref 限定成员函数时 GCC 错误消息的措辞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64705932/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com