Dangerous int-to-string conversions -- Andrzej Krzemieński

Note that the article doesn't mention to_string, which is the preferred C++11 way to convert an int to a string. But it does point out an issue -- you can assign an int to a string, including by accident.

Dangerous int-to-string conversions

by Andrzej Krzemieński

From the article:

And now, because int is implicitly convertible to char, our unexpected conversion from int to std::string ‘works’ (under some definition of ‘work’)...

Add a Comment

Comments are closed.

Comments (1)

0 0

Sektor said on May 9, 2014 02:56 AM:

Well, I have already proposed solution for problems like that (which span much wider than just string): prevent implicit conversion at the border of function call (for example, with the use of 'explicit' modifier).

The biggest problem is with filling a string with a series of one character: string::assign(size_t, char), which has quite a misleading towards another string::assign(const char*, size_t). Many people make a mistake with the fist one and call it with s.assign(' ', 27), which fills the string with 32 escape characters instead of 27 spaces.

If we could make this assign declared as:

void assign(size_t nch, explicit CharT ch);


This should prevent 27 from being implicitly converted to CharT and this mistaken call would be rejected.

This kind of explicit can be also defined librarywise and used as, e.g., 'explicit_t<CharT> ch', however this wrapper isn't perfect and having 'explicit' modifier in this place is natural and intuitive.