Is it safe to call temporary object's methods?

后端 未结 4 1940
离开以前
离开以前 2021-01-04 20:28

I have a function which shall return a char*. Since I have to concatenate some strings, I wrote the following line:

std::string other_text;
// ...
func((\"te         


        
4条回答
  •  余生分开走
    2021-01-04 20:50

    The C-string returned by calling c_str() on the temporary will be valid until the next call to c_str() on the temporary, which can never happen. The temporary itself hangs around to the end of the full expression it is part of (the return statement).

    If you were returning a std::string, everything would be hunkydory, as the string's copy constructor would be invoked in the return to take a copy. If you return a char *, then all bets are off, as the value you are returning will be disposed of when the function exits. This doesn't have anything specifically to do with the temporary, it is a general problem when returning char * - prefer to return std::strings instead.

提交回复
热议问题