Will C++ always prefer an rvalue reference conversion operator over const lvalue reference when possible?

  • A+
Category:Languages

When writing conversion operators, if I provide both a conversion to const T& and T&&, will C++ always prefer the rvalue operator when possible? This seems to be true in this small test:

#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; } 

prints:

 ╰─▸ ./test moving! 

But perhaps someone that speaks spec-ese better than I can verify?

 


There's no such preference.

Your example is actually showing preference for a non-const member function over a const one when called on a non-const object.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: