在可能的情况下,C++总是更喜欢rvalue引用转换运算符而不是const lvalue引用吗?

gct*_*gct 6 c++ c++11

在编写转换运算符时,如果我同时提供转换const T&T&&,C++是否总是更喜欢rvalue运算符?在这个小测试中,这似乎是正确的:

#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;
}
Run Code Online (Sandbox Code Playgroud)

打印:

 ??? ./test
moving!
Run Code Online (Sandbox Code Playgroud)

但也许有人能说出比我能验证的更好的规格吗?

T.C*_*.C. 7

没有这样的偏好.

在非const对象上调用时,您的示例实际上显示了对const const的非const成员函数的首选项.

  • 这将是模棱两可的. (2认同)