The temporary expression returned by foo() (and substr() ) will continue to exist until the end of the bar call (after the chain of method calls), this is safe.
int main() { A a; bar(a.foo().c_str());
The classic case of undefined behavior:
int main() { A a; const char* charPtr = a.foo().c_str(); printf("%s", charPtr); }
A temporary std::string , a pointer to its buffer is returned by c_str() , and the temporary one goes out of scope and is destroyed. charPtr now a pointer pointing to an invalid location (dead std::string ).
source share