C++ 临时字符串的生存期

gim*_*ilk 4 c++ string temporary

抱歉,我知道存在类似的问题,但我仍然不完全清楚。以下安全吗?

void copyStr(const char* s)
{
    strcpy(otherVar, s);
}

std::string getStr()
{
    return "foo";
}

main()
{
    copyStr(getStr().c_str());
}
Run Code Online (Sandbox Code Playgroud)

临时 std::string 将存储 getStr() 的返回值,但它的寿命是否足以让我将其 C 字符串复制到其他地方?或者我必须明确地为其保留一个变量,例如

std::string temp = getStr();
copyStr(temp.c_str());
Run Code Online (Sandbox Code Playgroud)

MSa*_*ers 5

是的,很安全。临时 fromgetStr一直存在到它出现的完整表达式的末尾。该完整表达式是调用copyStr,因此它必须在临时 fromgetStr被销毁之前返回。这对你来说已经足够了。