Is it safe to call temporary object#39;s methods?(调用临时对象的方法是否安全?)
问题描述
我有一个返回 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.
这篇关于调用临时对象的方法是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:调用临时对象的方法是否安全?
基础教程推荐
- C语言 详解字符串基础 2023-03-27
- centos 7 vscode cmake 编译c++工程 2023-09-17
- C语言编程C++旋转字符操作串示例详解 2022-11-20
- C++实战之二进制数据处理与封装 2023-05-29
- [c语言-函数]不定量参数 2023-09-08
- [C语言]二叉搜索树 2023-09-07
- C++实现ETW进行进程变动监控详解 2023-05-15
- C语言实现宾馆管理系统课程设计 2023-03-13
- 全面了解C语言 static 关键字 2023-03-26
- 带你深度走入C语言取整以及4种函数 2022-09-17
