mercredi 20 novembre 2019

what are the overload resolution rules of list-initialization

there are some codes here

#include <iostream>
struct A {
    A(int) {}
};
struct B {
    B(A) {
        std::cout<<"0"<<std::endl;
    }
    B(B const&) {
        std::cout << "1" << std::endl;
    }
    B(B&&) {
        std::cout << "2" << std::endl;
    }
};
int main() {
    B b00; // this is ok  #1
    B b( {0} ); //this is error #2
}

g++ report:

main.cpp: In function ‘int main()’:
main.cpp:17:11: error: call of overloaded ‘B(<brace-enclosed initializer list>)’ is ambiguous
  B b({ 0 });
           ^
main.cpp:12:2: note: candidate: B::B(B&&)
  B(B&&) {
  ^
main.cpp:9:2: note: candidate: B::B(const B&)
  B(B const&) {
  ^
main.cpp:6:2: note: candidate: B::B(A)
  B(A) {

clang report:

main.cpp:17:4: error: call to constructor of 'B' is ambiguous
        B b({ 0 });
          ^ ~~~~~
main.cpp:6:2: note: candidate constructor
        B(A) {
        ^
main.cpp:12:2: note: candidate constructor
        B(B&&) {
        ^
main.cpp:9:2: note: candidate constructor
        B(B const&) {
        ^
1 error generated.

{0} will convert to temporary object A and the contructor B(A) will be selected, #1 and #2 are all the "direct-constructor" form ,why #1 is ok ,#2 has three candidate constructor and is ambiguous?

Aucun commentaire:

Enregistrer un commentaire