Implicit VS Explicit Conversion

前端 未结 4 587
[愿得一人]
[愿得一人] 2020-11-30 23:19

The C++ Standard Library by Nicolai M. Josuttis states:

There is a minor difference between

X x;
Y y(x) //explicit conversion

and

4条回答
  •  天涯浪人
    2020-11-30 23:55

    one uses the assignment operator though

    No, it does not. It calls the constructor directly.

    The reason why one is explicit and one is implicit is because implicit conversions can happen when you don't want them to. Explicit ones cannot. The easiest example of this is bool.

    Let's say that you invent some type which can be either true or false- like a pointer. Then let's further say that you decide that in order to make life easier for your users, you let it convert to bool implicitly. This is great- right up until the point where one of your users does something dumb.

    int i = 0;
    i = i >> MyUDT();
    

    Oh wait- why does that even compile? You can't shift a MyUDT at all! It compiles because bool is an integral type. The compiler implicitly converted it to a bool, and then to something that can be shifted. The above code is blatantly dumb- we only want people to be able to convert to a bool, not a bool and anything else that a bool might want to do.

    This is why explicit conversion operators were added to C++0x.

提交回复
热议问题