非空终止char数组的std :: string_view大小的差异

Jay*_*Phi 1 c++ string-view c++17

我正在使用不同编译器的std :: string_view,并注意到每个编译器在使用非null终止的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';
}
Run Code Online (Sandbox Code Playgroud)

输出: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
Run Code Online (Sandbox Code Playgroud)

输出: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
Run Code Online (Sandbox Code Playgroud)

输出: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
Run Code Online (Sandbox Code Playgroud)

Edg*_*jān 9

来自cppreference.com:

constexpr basic_string_view(const CharT*s);

构造s指向的以null结尾的字符串的视图,不包括终止空字符.

您的测试程序会导致未定义的行为,正如TC在上面的评论中提到的那样.

  • `string_view` 有另一个接受 `count` 作为输入的构造函数,例如: `string_view str_v{ foo, sizeof(foo) };` (2认同)