nostd :: string_view的构造函数除外

问题描述 投票:2回答:1

根据the documentation,std :: string_view具有一个接受const char *std::size_t且未声明为noexcept的构造函数:

constexpr basic_string_view(const CharT* s, size_type count);

[另一方面,the documentation还声明用户定义的文字operator""sv,在我所见过的所有实现中,都是该构造函数的简单包装,已声明为noexcept

constexpr std::string_view operator "" sv(const char* str, std::size_t len) noexcept;

您知道这种差异的原因吗?构造函数什么时候可以抛出?

c++ c++17 noexcept user-defined-literals string-view
1个回答
0
投票
对于构造函数

constexpr basic_string_view(const CharT* s, size_type count);

您可以将任何内容作为字符串传递:

char c{'X'}; std::string_view sv{&c, 100}; // oops

因此,此函数没有wide contract(即接受所有输入),并且未按noexcept标记为N3279 Conservative use of noexcept in the Library-标记为noexcept会阻止库包含测试以帮助用户发现错误的代码。他们的代码(当然是在调试模式下)。 (有关更多信息,请参见noexcept。)


另一方面,UDL运算符

Can std::string::compare(const char*) throw an exception?

通常在翻译文字时由语言调用:

constexpr std::string_view operator "" sv(const char* str, std::size_t len) noexcept;

不可能传递无效的指针值,因此运算符为using std::string_literals;
auto sv = "foo"sv;
。当然,您可以使用无效值直接调用该运算符,但这不是标准库应该处理的问题。
© www.soinside.com 2019 - 2024. All rights reserved.