Note that my_string+"My_Second_Text"
is a temporary std::string
, which will be destroyed after the expression immediately. That means my_pointer
will become dangled at once, because the char array it's supposed to point to has been destroyed along with the destroy of the temporary std::string
; note that the returned char array belong to std::string
, it's not standalone. Then, deference on dangled pointer would lead to UB.
string my_string="My_First_Text";
char * my_pointer=(char *)(my_string+"My_Second_Text").c_str();
// the temporary constructed from my_string+"My_Second_Text" has been destroyed
// my_pointer is dangled now; deference on it is UB
Using named variable instead of temporary will be fine. e.g.
string my_string = "My_First_Text";
my_string += "My_Second_Text";
const char * my_pointer = my_string.c_str();
BTW: The return type of std::basic_string::c_str is const char*
, and any modification on it is UB. So trying to convert it to char*
explicitly is dangerous.
Writing to the character array accessed through c_str()
is undefined behavior.
const
to the second line and no more warning, but the problem is still there. – Portulaca