In this statement:
const char *str = fun().c_str();
// oops, str is invalid, since the temporary has been destroyed
fun
returns a temporary std::string
, and you're taking a pointer to that with c_str
. However, that temporary dies at the end of the full expression, in this case at the ;
. So you're left with a pointer that points to memory that no longer exists, which is what the sanitizer is telling you about.
You can fix this by assigning the returned std::string
to an l-value, and this will ensure that the pointer you take with c_str
will live till the end of main
.
auto temp = fun();
const char *str = temp.c_str();
// ok, str is valid, since temp has not been destroyed
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…