Your program has undefined behavior .
When you pass "hello" to test , a temporary std::string object is created, and c is created from this string (which is just a pointer to the data of the string object).
When the function call ends, the temporary std::string object is destroyed, and c becomes a dangling pointer. Use this undefined behavior again.
In your case, the second temporary std::string object has the same memory address as the first, so c points to this data. This is not guaranteed.
source share