我正在用不同的编译器玩std::string_view并注意到每个编译器在使用非空终止的 char 数组初始化std::string_view时打印出不同的大小。
似乎每个编译器在打开优化时都打印出正确的大小,但在关闭优化时打印出错误的大小(GCC 除外,它在两种情况下都打印出正确的大小)。
我的问题是:为什么会这样?
代码:
// test.cpp
#include <iostream>
#ifdef __MINGW32__
#include <experimental/string_view>
#elif _MSC_VER
#include <string_view>
#endif
int main()
{
const char foo[3]{ 'f','o','o' };
#ifdef __MINGW32__
std::experimental::string_view str_v{ foo };
#elif _MSC_VER
std::string_view str_v{ foo };
#endif
std::cout << sizeof(foo) << " " << str_v.size() << '\n';
}
输出:Visual C++ 19.00.24619.0
3 5 // cl /Zi /std:c++latest /EHsc /nologo /W4 test.cpp
3 3 // cl /O2 /std:c++latest /EHsc /nologo /W4 test.cpp
输出:Clang 4.0.0-r282394(使用 MinGW-w64)
3 4 // clang++ -g --target=x86_64-w64-mingw32 -std=c++1z -Wall -o test.exe test.cpp
3 3 // clang++ -02 --target=x86_64-w64-mingw32 -std=c++1z -Wall -o test.exe test.cpp
输出:GCC 6.2.0 (MinGW-w64)
3 3 // g++ -g -std=c++1z -Wall -o test.exe test.cpp
3 3 // g++ -O2 -std=c++1z -Wall -o test.exe test.cpp