我在使用不同编译器的 std::string_view 时发现每个编译器在使用非空值初始化 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
最佳答案
来自cppreference.com :
constexpr basic_string_view(const CharT* s);
Constructs a view of the null-terminated character string pointed to by s, not including the terminating null character.
您的测试程序导致未定义的行为,因为 T.C.在上面的评论中已经提到。
关于c++ - 非空终止字符数组的 std::string_view 的大小差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40202151/