C++ c_str() 和 临时变量

昨天晚上讨论了一个问题, 程序如下:

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()。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值