why implicit conversion is harmful in C++

后端 未结 8 1670
臣服心动
臣服心动 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:43

    Use explicit when you would prefer a compiling error.

    explicit is only applicable when there is one parameter in your constructor (or many where the first is the only one without a default value).

    You would want to use the explicit keyword anytime that the programmer may construct an object by mistake, thinking it may do something it is not actually doing.

    Here's an example:

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

    With the following code you are allowed to do this:

    int age = 29;
    //...
    //Lots of code
    //...
    //Pretend at this point the programmer forgot the type of x and thought string
    str s = x;
    

    But the caller probably meant to store "3" inside the MyString variable and not 3. It is better to get a compiling error so the user can call itoa or some other conversion function on the x variable first.

    The new code that will produce a compiling error for the above code:

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

    Compiling errors are always better than bugs because they are immediately visible for you to correct.

提交回复
热议问题