为什么不同编译器使用c++字符串+字符串临时对象有区别

Why is there a difference between using c++ string+string temporary object by different compilers?

本文关键字:字符串 临时对象 有区别 c++ 编译器 为什么不      更新时间:2023-10-16

请查看此代码。

#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构建发布版本(在上进行优化),您可能会看到相同的行为。