Converting between a string and an int is a problem without a satisfactory solution in C++. Solutions range from itoa , strtol , through std::stringstream to boost::lexical_cast , but every one has its downsides. You have probably already figured out what to do yourself, but have you ever seen this:

// BEWARE ! bool convert(std::string& to, const int& from) { to = from; return true; }

Is this even legal C++? Yes, it compiles fine! Do you know what it does?

You might find it surprising or not that std::basic_string has an assignment from its underlying CharT . So in order to have a one-character string, you can type:

std::string s; s = 'c';

This is surprising, because you do not have a corresponding (in terms of argument types) constructor. In order to achieve the same effect in a single-phase initialization, you have to use a different constructor:

std::string s(1, 'c');

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

std::string s; convert(s, 100); assert(s == "d"); // assuming ASCII encoding

I consider the existence of this assignment a security bug. I was hit by it when I changed the type of one variable in my program from int to std::string and expected that compiler would warn me in all places where I treated my new string as an int . Well, it didn’t because the compiler likes the mixed assignment. Perhaps I shouldn’t have had such an expectation, but what can I say: I did have it. And I want to warn you lest you should fall into the same trap.

Advertisements