Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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?

like image 881
gct Avatar asked Aug 08 '18 20:08

gct


1 Answers

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.

like image 87
T.C. Avatar answered Oct 12 '22 23:10

T.C.