Pitfall of C++ string for Java programmers
Yesterday, I saw a young colleague struggle with C++ string, so I decided to take a look to see what was going on. He was more familiar with Java than with C++. He was creating a string, and it didn’t come out exactly the way he wanted. The code looked similar to the following:
-
string str("This is a test" + 2);
-
std::out << "’" << str1 << "’" << std::endl;
It always displayed:
'is is a test'
And not the way he wanted, which should be:
'This is a test2'
This is very understandable, as he came from Java background, where the following Java code:
would have produced exactly the result he wanted.
The C++ code above does not concatenate two strings to form a new string. In fact, it is a pointer arithmetic. One I changed his code to the following, it was much clearer:
-
const char *ptr = "This is a test";
-
std::string str1(ptr + 2);
For him, pointer arithmetic is obvious now. It was not the first time someone fell into this pitfall, and unfortunately, it won’t be the last either.