调用临时对象的方法是安全的吗? [英] Is it safe to call temporary object's methods?

查看:169
本文介绍了调用临时对象的方法是安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数应该返回一个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;
// ...
return ("text" + other_text).c_str();

我知道我可以避免命名我想要返回的字符串的问题。我只想借机会提出一个更一般的问题:
是否可以安全地调用临时变量的方法?是标准兼容吗?

I know that I could avoid the question naming the string I want to return. 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.

这篇关于调用临时对象的方法是安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆