What are the differences between string.c_str()
and &string[0]
?
Regarding performance my guess is that &string[0]
is a little faster than string.c_str() as it doesn’t require a function call.
Regarding safety and stability common sense tells me that string.c_str()
should have some checks implemented, but I don’t know, that’s why I’m asking.
2
In C++98 there is no guarantee that the internal array is null terminated; in other words string.data()[string.size()]
results in undefined behavior. The implementation will then reallocate the array with the null termination when c_str()
is called but can leave the null terminator off when it isn’t.
This also means that &string[0]
is not guaranteed to be null terminated (it is essentially a detour to data()
)
In C++11 the null termination guarantee is specified so string.data()==string.c_str()
is always valid.
3