#include <string>
#include <iostream>
void Print(const char* s) {
std::cout << s << std::endl;
}
std::string GetString() {
std::string ret;
ret = "Is this defined behavior?";
return ret;
}
int main() {
Print(GetString().c_str());
}
这段代码似乎可以在三大编译器上可靠地工作。我担心它实际上可能不是定义的行为,是否可能会破坏字符串,使 c_str() 返回的指针在调用 Print 函数之前悬空?
这是完全明确定义的行为。
GetString()
返回一个临时的std::string
,当创建它的完整表达式结束时,它将被销毁。这意味着在 ;
退出后,它会在 Print()
上被销毁,因此 c_str()
指针不会在 Print()
内部悬空。