下面的代码可以正常工作,但为什么这是正确的代码?为什么 "c_str()" 指向 foo() 返回的临时对象是有效的?我认为当进入 bar() 时,这个临时对象已经被销毁了,但似乎并非如此。因此,现在我假设 foo() 返回的临时对象将在调用 bar() 后被销毁 - 这是正确的吗?为什么?
std::string foo() {
std::string out = something...;
return out;
}
void bar( const char* ccp ) {
// do something with the string..
}
bar( foo().c_str() );