C ++ string lifetime

I apologize because I know similar questions, but I'm still not entirely clear. Is the following safe?

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

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

main()
{
    copyStr(getStr().c_str());
}

Temporary std :: string will keep returning from getStr (), but will it live long enough so that I can copy its C-string to another location? Or should I explicitly store a variable for it, e.g.

std::string temp = getStr();
copyStr(temp.c_str());
+4
source share
3 answers

Yes, it is safe. The temporary of getStrlives to the end of the full expression in which it appears. A full expression is a challenge copyStr, so it must return to a temporary one getStr. This is more than enough for you.

+3
source

. ,

copyStr(getStr().c_str());

getStr() s copyStr. copyStr. , , , .

+2

:

...
{
  std::string tmp = getStr();
  //tmp live
  ...
}
//tmp dead
...

, .

: , ( ). )

copyStr(getStr().c_str()); rvalue copyStr()

0

Source: https://habr.com/ru/post/1546536/


All Articles