【问题标题】:Differences in size of std::string_view of non-null terminated char array非空终止字符数组的 std::string_view 大小差异
【发布时间】: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


【解决方案1】:

来自cppreference.com

constexpr basic_string_view(const CharT* s);

构造一个空终止字符串指向的视图 to by s,不包括终止空字符。

您的测试程序导致未定义的行为,如 T.C.在上面的评论中提到过。

【讨论】:

  • string_view 有另一个接受count 作为输入的构造函数,例如:string_view str_v{ foo, sizeof(foo) };
  • @RemyLebeau 是的,当然,但我决定不提。
猜你喜欢
  • 1970-01-01
  • 2011-06-09
  • 2013-08-28
  • 2013-10-22
  • 1970-01-01
  • 2012-08-14
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
相关资源
最近更新 更多