C ++: casting operator versus operator assignment and conversion priority

Let this code:

Test1 t1; Test2 t2; t1 = t2; 

I believe that there are three (or more?) Ways to implement t1 = t2

  • reload Test1 statement in Test1
  • for operator like overload in Test2
  • to create the transform constructor Test1(const Test2&)

According to my GCC testing, this is the priority of use:

  • assign an operator
  • conversion constructor and type casting operator (ambiguous)
  • const conversion constructor and const type merge operator (ambiguous)

Please help me understand why this priority.

I use this code for testing (uncomment some lines to try)

 struct Test2; struct Test1 { Test1() { } Test1(const Test2& t) { puts("const constructor wins"); } // Test1(Test2& t) { puts("constructor wins"); } // Test1& operator=(Test2& t) { puts("assign wins"); } }; struct Test2 { Test2() { } // operator Test1() const { puts("const cast wins"); return Test1(); } // operator Test1() { puts("cast wins"); return Test1(); } }; int main() { Test1 t1; Test2 t2; t1 = t2; return 0; } 
+6
source share
1 answer

Statement t1 = t2; is equivalent to:

 t1.operator=(t2); 

The usual rules for overload resolution now apply. If there is a direct match, then the selected one. If not, then implicit conversions are considered for use with the (automatically generated, implicitly determined) copy-assignment operator.

There are two possible implicit user-defined conversions. All user-defined conversions are equal, and if both are defined, overload is ambiguous:

  • Convert t2 to Test1 using the conversion constructor Test1::Test1(Test2 const &) .

  • Convert t2 to Test1 using the translation operator Test2::operator Test1() const .

+13
source

Source: https://habr.com/ru/post/924934/


All Articles