简体   繁体   中英

Copy-initialization with implicit conversion in c++

class Foo {
  public:
    Foo(float b) {}
};

class Bar {
  public:
    Bar(Foo foo) {}
};

int main(int argc, char *argv[]) {
    Bar b1(3.0f);  // accept, one implicit convertion happens there.
    Bar b2 = 3.0f;  // error: no viable conversion from 'float' to 'Bar'
    return 0;
}

Why does the second expression fail to compile? I expected that it would call the same converting constructor as same as the first expression.

From [dcl.init]:

Otherwise (ie, for the remaining copy-initialization cases), user-defined conversion sequences that can convert from the source type to the destination type or (when a conversion function is used) to a derived class thereof are enumerated as described in 13.3.1.4, and the best one is chosen through overload resolution (13.3).

We can invoke a user-defined conversion that is from the source type directly to the target type. That is, if we had Bar(float ) , we would consider that constructor. However, in this case, our candidate is simply Bar(Foo ) , which does not take a float .

You are allowed zero or one user-defined conversion. In the direct-initialization case, we simply call Bar(Foo ) which invokes one user-defined conversion ( float --> Foo ). In the copy-initialization case, we are looking for a conversion sequence from float (the source type) all the way to Bar (the destination type), which would involve two user-defined conversions ( float --> Foo , Foo --> Bar ), hence the error.

The second type of initialization is called copy-initialization and uses copy constructor. Therefore, this type of initialization expects the right side is convertible to Bar.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM