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

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

问题描述

我有一个返回 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.

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

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