c++ - 非空终止字符数组的 std::string_view 的大小差异

标签 c++ c++17 string-view

我在使用不同编译器的 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/

相关文章:

C++ 计算器跳过 Else 语句

c++ - 在 C++ 中读取带有引号的 CSV/文本文件

c++ - 在函数中传入和修改数组

c++ - 如何将结构/union 数组的成员传递给函数

c++ - 合并两个 std::set 和(尚未) std::set::merge()

c++ - 在 C++ 中,如何制作一个可以包含相同变体 vector 的变体?

c++17 - 为什么没有从 std::string_view 到 std::string 的隐式转换?

使用递归函数时的 C++ 堆栈溢出

c++ - 如何将 boost::string_view 转换为 std::string_view?

c++ - 为什么 C++ 标准中没有 std::basic_string 类的构造函数,其参数为 std::string_view 类型