While trying to get some insights on compilers behaviors (gcc and clang) related to this question, I just did not understand why there was a difference in the 3rd case (presented below) between gcc and clang. The question is not about the correctness of such a conversion API (especially the reference case).
Could you please help me understand what is the expected behavior (from a c++ standard point of view) in this scenario?
EDIT: As stated in the comments, this behavior is observable in clang only from -std=c++17. Before that, reference conversion is used as in gcc.
EDIT2: Note that the right behavior "seems" to be gcc as the implicit this
argument is not const
thus the non-const overload is preferred...
Here is the sample code:
struct SInternal {
SInternal() = default;
SInternal(const SInternal&) {
std::cout << "copy ctor" << std::endl;
}
int uuid{0};
};
struct S {
SInternal s;
S() = default;
operator SInternal() const {
std::cout << "copy conversion" << std::endl;
return s;
}
operator SInternal& () {
std::cout << "ref conversion" << std::endl;
return s;
}
};
int main() {
S s;
const S s2;
// 1-
//SInternal si = s; // no ambiguity, ref conversion
//SInternal si = s2; // no ambiguity, copy conversion
// 2-
// SInternal& si = s; // no ambiguity, ref conversion
// SInternal& si = s2; // no viable conversion operator SInternal& not const
// Case 3- WHAT IS THE CORRECT EXPECTED BEHAVIOR HERE?
SInternal si(s); // no ambiguity but clang uses copy conversion
// while gcc uses ref conversion
//SInternal si(s2); // no ambiguity, copy conversion
// 4-
//SInternal si = std::move(s); // no ambiguity ref conversion
std::cout << "test " << si.uuid << std::endl;
}
Thanks for your help.
-std=c++14
. I think RVO in c++17 makesoperator T()
is better thanoperator T&()
+T(T const&)
. and in c++14,operator T&()
+T(T const&)
is better thanoperator T()
+T(T const&)
, becauseT&
is better matched withT const&
thanT
. refer to: over.match.best – RedFogoperator T()
andoperator T&
are both exact match , so choosingoperator T&()
is better becauses
is non-const. so waiting for more answer as well. – RedFog