Yes, you are right regarding
std::string::c_str.
Indeed,
Returns a pointer to a null-terminated character array with data equivalent to those stored in the string.
However, there are a few considerations which probably misleading you.
First of all, the statement:
a = a.c_str();
is semantically a no-operation.
You get the const char*
(i.e. "Hello World\0"
) and assign it to a
.
However a
is a std::string
, it is a class designed to abstract a "string type" in C++. It handles automatically the '\0'
, transparently. The user is not supposed to care about the managing of it1.
The trick is inside std::string::operator=(const char*)
.
Replaces the contents with those of null-terminated character string pointed to by s as if by assign(s, Traits::length(s)).
The last point, about string concatenation.
a + string("aaa");
As previously, in this case, the operator std::string::operator+
will handle the '\0'
.
Shortly, it behaves like:
"Hello World\0" + "aaa\0" ===> "Hello Worldaaa\0"
It will care about the "inner '\0'
" returning a conforming null-terminated string.
1 Unless he/she is playing with the internal memory.