我有这小段代码:
struct Res { };
struct A {
virtual Res &&foo();
};
struct B : A {
Res &foo() override;
};
它在GCC中编译,但不在Clang中编译:https://godbolt.org/z/65rffW。根据引用的标准语言here,左值引用不是右值引用的协变返回类型。
为什么GCC不会发出错误?
最佳答案
这实际上是标准缺陷报告的主题,这是一个非常古老的报告:
- Covariant functions and lvalue/rvalue references Section: 11.7.3 [class.virtual] Status: CD2 Submitter: James Widman Date: 1 September, 2009
[Voted into WP at March, 2010 meeting.]
11.7.3 [class.virtual] paragraph 5 requires that covariant return types be either both pointers or both references, but it does not specify that references must be both lvalue references or both rvalue references. Presumably this is an oversight.
Proposed resolution (February, 2010):
Change 11.7.3 [class.virtual] paragraph 5 bullet 1 as follows:
...If a function D::f overrides a function B::f, the return types of the functions are covariant if they satisfy the following criteria:
- both are pointers to classes, both are lvalue references to classes, or both are rvalue references to classes106
...
从http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#960
The code is ill-formed,Clang和MSVC(至少)确实解决了该问题,而GCC没有解决,它无法识别格式错误的代码。
错误报告:https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99664
关于c++ - GCC : rvalue ref and lvalue ref are covariant return types中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66698168/