Is it safe to call temporary object's methods?

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

    It is safe to call methods of temporary variables, but not safe to return a char* of a temporary variable for later use.

    This char* points to a buffer that will be freed soon. Once it is freed you will have a pointer to an invalid region in memory.

    Instead please return an std::string object.

提交回复
热议问题