Is it safe to use (str1 + str2).c_str()? [duplicate]

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 😉 )

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)