【问题标题】:Constructing a vector of string_views from an initializer_list从 initializer_list 构造 string_views 的向量
【发布时间】:2021-01-21 02:05:36
【问题描述】:

我正在尝试从 initializer_list< const char * > 构造 string_views 的 vector,这在 GCC 9 上运行良好,但在更新到 GCC 10 后,它在运行时崩溃。

#include <vector>
#include <string_view>
#include <cstdio>

int main()
{
    std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." } };
    printf( "%s %zu\n", v[0].data(), v[0].length() );
    printf( "%s %zu\n", v[1].data(), v[1].length() );

    return 0;
}

Clang 还可以处理代码,什么给出?

链接:https://godbolt.org/z/6s1c61

【问题讨论】:

  • @TedLyngmo 确实如此,这恰好在更新编译器后引起了我的注意,所以我想找出原因:)

标签: c++ gcc c++20


【解决方案1】:

在这个变量定义中

std::vector< std::string_view > const v { { "Before.", "Afterrrrrr." } };

你不小心使用了这个新的 C++20 string_view 构造函数:

template<class It, class End>
constexpr basic_string_view(It first, End last);

因此,您只需使用 "Afterrrrrr." 的开头构造 一个 string_view 作为结束迭代器。这使得程序具有未定义的行为。

这是正确的方法:

std::vector< std::string_view > const v { "Before.", "Afterrrrrr." };

【讨论】:

  • 问题也随之消失,-std=c++17。构造函数被添加到this commit中的libstdc++中,实现了P1391R4
猜你喜欢
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-31
  • 2021-02-12
  • 2012-09-08
相关资源
最近更新 更多