Is it safe to call temporary object's methods?

后端 未结 4 1927
离开以前
离开以前 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:57

    You are allowed to call methods on temporaries, however you have to be careful about object lifetimes -- in particular, if you have a function that returns c_str() called on a temporary std::string, that string object will be destroyed when the function returns.

    Your code above suffers from this problem.

提交回复
热议问题