这是代码:
使用gcc 6.2.0编译:
int main()
{
char* a = "abc"; // Should be 'const char*', but no warnings whatsoever on VS
a[1] = 'e'; // No warnings on VS either
std::cout<< a << " " << a[1];
return 0;
}
使用gcc 6.2.0编译:
>g++ -O2 -o Test Test.cpp
Test.cpp: In function ‘int main()’:
Test.cpp:5:15: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
char* a = "abc";
^~~~~
>./Test
Segmentation fault (core dumped)
使用Visual Studio 2015.3编译:
>cl /EHsc /W4 /WX /O2 Main.cpp
Microsoft (R) C/C++ Optimizing Compiler Version 19.00.24215.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
Main.cpp
Microsoft (R) Incremental Linker Version 14.00.24215.1
Copyright (C) Microsoft Corporation. All rights reserved.
/out:Main.exe
Main.obj
>Main.exe
abc e
HUH?^
不使用/O2
编译也没有警告,但运行时崩溃。
这是一个VS编译器的错误还是我漏了什么?
a[1]
是e
?它是一个临时变量吗? - user7079790char* str = "foo";
或依赖于这种行为来进行某些操作,或者出于其他一些不太合理的模糊原因 :) - Rakete1111