【发布时间】:2016-10-23 11:00:55
【问题描述】:
我用不同的编译器玩弄 std::string_view 并注意到每个编译器在用非 null 初始化 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
【问题讨论】:
-
未定义的行为是未定义的。
-
如下所述,您需要使用 '\0' 对字符串进行空终止,或者使用为您以空终止的 const char* 字符串。
标签: c++ c++17 string-view