It’s not safe in your example. It’s safe however in
printf("%s\n", (a + b).c_str());
The reason is that temporary values (like the result of a + b
) are destroyed at the end of the full expression. In your example the const char *
survives the full expression containing the temporary and dereferencing it is undefined behaviour.
The worst part of “undefined behaviour” is that things may apparently work anyway… (UB code crashes only if you’re making your demo in front of a vast audience that includes your parents 😉 )