Is this well defined behavior?
const char* p = (std::string("Hello") + std::string("World")).c_str();
std::cout << p;
I am not sure. Reasons?
Is this well defined behavior?
const char* p = (std::string("Hello") + std::string("World")).c_str();
std::cout << p;
I am not sure. Reasons?
No, this is undefined behavior. Both
std::string
temporaries and the temporary returned byoperator+
only live until the end of the initialization of yourconst char*
(end of full expression). Then they are destroyed andp
points to uncertain memory.No the behaviour is undefined because
p
points to deallocated storage instd::cout << p;
A temporary is created to hold
std::string("Hello") + std::string("World")
. C-style string is then retrived from that object. At the end of the expression that temporary is destroyed leavingp
pointing to a deallocated storage.Using
p
then invokes Undefined Behavior.12.2/4 says
I recently read this excellent book http://www.amazon.co.uk/Gotchas-Avoiding-Addison-Wesley-Professional-Computing/dp/0321125185/ref and if I recall correctly this is pretty much one of the examples given there.
I believe the data returned from
c_str
is only valid as long as the string object that returned it is live. The string objects in your example are only live for the duration of the expression.it won't compile because of a missing semi-colon:
NOW the rule applies that the temporary is deleted at the end of the expression it is used in, which is at the semicolon. So you have a pointer to deleted memory which causes undefined behaviour.