昨天晚上讨论了一个问题, 程序如下:
int function()
{
std::string str("hello");
const char *p = (str + "world").c_str();
std::cout << p << std::endl;
return 0;
}打印输出p的时候,发现为空。 然后就是思考。。 为什么会为空呢。。 如果我们如如下程序写的话, 就能正常打印helloworld.
str += "world";
const char *p = str.c_str();其实也就是在执行str+"world"之后, 该变量为临时变量, string调用析构函数。free掉了这块内存。 自然c_str()函数返回的也是null。
其实程序一的代码可以解析为:
string function1(string str1, string str2)
{
std::string str_tmp(str1);
str_tmp += str2;
return str_tmp;
//return "helloworld";
}
int function()
{
std::string str("hello");
const char *p = function1(str, "world").c_str();
std::cout << p << std::endl;
return 0;
}
自然,当function1() 返回 str_tmp字符串之后, str_tmp自然就free掉了。 然后再调用的c_str()。
本文探讨了C++中使用临时变量进行字符串连接后出现空指针的问题。通过具体示例解释了为何直接拼接字符串会导致内存被释放,并提出了正确的实现方式。
781

被折叠的 条评论
为什么被折叠?



