在编写转换运算符时,如果我同时提供对const T&
和T&&
的转换,C++是否总是尽可能首选右值运算符? 在这个小测试中,这似乎是正确的:
#include <algorithm>
#include <stdio.h>
struct holds {
operator int&&() { printf("moving!n"); return std::move(i); }
operator const int&() const { printf("copying!n"); return i; }
private:
int i = 0;
};
int main() {
holds h;
int val = h;
}
指纹:
╰─▸ ./test
moving!
但也许有人说得比我更清楚?
没有这样的偏好。
您的示例实际上显示了在非常量对象上调用时对非常量成员函数的偏好而不是常量成员函数。
所以我没有精力和时间把自己埋在这个标准中。我相信有人会。
但是,我想指出您的假设是错误的。而且您错过了一个关键信息:一个运算符是const
,一个不是,事实证明这是您情况的决定性因素,而不是&&
与const &
。我看看:
两种方法都是可变的,可变的对象:
operator int&&();
operator const int&() ;
holds h;
int val = h; // compile error
给出错误:
因此,您会看到两个转换运算符相等,并且没有一个是首选的,因此存在歧义。从"保留"到"int"的转换不明确
两种方法都是可变的,常量对象:
operator int&&();
operator const int&() ;
const holds h;
int val = h; // error no viable method
好吧,这是一个简单且无趣的方法:不能在 const 对象上调用可变方法
&&
可变、const&
常量、对象可变
operator int&&();
operator const int&() const;
holds h;
int val = h; // calls holds::operator int&&()
现在首选可变方法,因为对象是可变的
&&
可变、const&
常量、对象常量
operator int&&();
operator const int&() const;
const holds h;
int val = h; // calls holds::operator int const&() const
现在,const
方法是唯一的选择,因为不能在 const 对象上调用可变方法。