用户定义的到右值引用的转换无效

invalid user-defined conversion to rvalue reference

本文关键字:引用 转换 无效 定义 用户      更新时间:2023-10-16

除了4.9.0-4.9.4 和 9.1.0 之外,大多数版本 gcc 都认为这个 C++11 代码格式不正确,除非同时使用-pedantic-fpermissive选项,这背后的原因是什么? 叮当编译了它。

struct A {
int a;
operator int() &&  { return a; }
operator int&() &  { return a; }
};
void b(int &&) {}
int main()
{
b(A{});
}

输出类似于:

prog.cc: In function 'int main()':
prog.cc:11:10: error: invalid user-defined conversion from 'A' to 'int&&' [-fpermissive]
b(A{});
^
prog.cc:4:5: note: candidate is: A::operator int&() & <near match>
operator int&() &  { return a; 

根据StoryTeller的评论,该问题显然与实现中的中间错误有关,并且它们修复了,可能的解决方案可能是:

#include <utility> //std::move
#include <iostream>
struct A {
int a;
operator int const& () const  { std::cout <<__PRETTY_FUNCTION__<<std::endl; return a; }
operator int&&() &&   { std::cout <<__PRETTY_FUNCTION__<<std::endl;  return std::move(a); }
};
void b(int &&) {}
void b(const int &) {}
int main()
{
b(A{});
b(std::move(A{}));
A a;
b(a);
}

输出:

A::operator int&&() &&
A::operator int&&() &&
A::operator const int&() const