为什么不同编译器使用c++字符串+字符串临时对象有区别
Why is there a difference between using c++ string+string temporary object by different compilers?
请查看此代码。
#include <iostream>
#include <string>
using namespace std;
int main() {
string hello = "Hello"
, world = "World";
const char *p = (hello+world).c_str();
cout << "STRING: " << p <<endl;
return 0;
}
我没有声誉,不能张贴图片,所以我会手写结果。
=Visual Studio 2013版本12.0.30110.00
STRING:
=Dev-C++版本4.9.9.2
STRING: HelloWorld
下面是Visual Studio编译的执行结果。
第二个由Dev-C++编译。
我想知道这有什么不同
我将期待你的答复。感谢:)
(hello+world).c_str()
仅在后面的;
之前有效。之后访问内存是未定义的行为。
Visual studio可能真的清除了内存,Dev-C++并不介意。尝试使用Visual studio构建发布版本(在上进行优化),您可能会看到相同的行为。
相关文章:
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 在不复制临时对象的情况下延长其生存期
- 为什么当我们有常量引用时创建临时对象?
- 程序如何'remember'临时对象?
- 返回对临时对象的引用
- 防止临时对象文件访问 MSVC 中的磁盘
- 是否可以在C++中移动临时对象的属性?
- 通过引用传递临时对象
- 临时C++对象是否为左值?
- 临时对象:术语澄清
- 存储对(可能)临时对象的引用是否合法,只要引用不比对象存活?
- 临时对象有身份吗?
- 临时对象上的运算符重载
- 如何在没有 std::move 的情况下移动临时对象
- 临时对象在C++中是不可避免的吗?
- C++ - 确定 const char* 是指向字符串文本对象还是动态对象
- 编译错误:临时对象构造函数中缺少参数
- 为什么写入临时字符串流对象只打印对象地址
- 当我从内联函数返回字符串时,会创建多少个临时对象
- 为什么不同编译器使用c++字符串+字符串临时对象有区别