调用临时对象的方法是否安全?

2022-01-23 00:00:00 string g++ c++ stl

我有一个返回 char* 的函数.由于我必须连接一些字符串,所以我写了以下行:

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(("text" + other_text).c_str());

我知道我可以避免命名我想使用的字符串的问题.我只是想借此机会提出一个更笼统的问题:调用临时变量的方法是否安全?是否符合标准?

I know that I could avoid the question naming the string I want to use. I just want to take the chance to make a more general question: is it safe to call methods of temporary variables? is it standard compliant?

推荐答案

调用临时变量的方法是安全的,但返回临时变量的char*供以后使用是不安全的.

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

这个 char* 指向一个即将被释放的缓冲区.一旦它被释放,你将有一个指向内存中无效区域的指针.

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.

请返回一个 std::string 对象.

Instead please return an std::string object.

相关文章