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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With