Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

why implicit conversion is harmful in C++

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

For example

Foo {

 public:
 explicit Foo(int i) {}
}

My question is, under what condition, implicit conversion should be prohibited? Why implicit conversion is harmful?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...