why implicit conversion is harmful in C++

后端 未结 8 1668
臣服心动
臣服心动 2020-12-03 10:22

I understand that the keyword explicit can be used to prevent implicit conversion.

For example

Foo {

 public:
 explicit Foo(int i) {}
}
         


        
8条回答
  •  感动是毒
    2020-12-03 10:38

    To expand Brian's answer, consider you have this:

    class MyString
    {
    public:
        MyString(int size)
            : size(size)
        {
        }
    
        // ...
    };
    

    This actually allows this code to compile:

    MyString mystr;
    // ...
    if (mystr == 5)
        // ... do something
    

    The compiler doesn't have an operator== to compare MyString to an int, but it knows how to make a MyString out of an int, so it looks at the if statement like this:

    if (mystr == MyString(5))
    

    That's very misleading since it looks like it's comparing the string to a number. In fact this type of comparison is probably never useful, assuming the MyString(int) constructor creates an empty string. If you mark the constructor as explicit, this type of conversion is disabled. So be careful with implicit conversions - be aware of all the types of statements that it will allow.

提交回复
热议问题