根据 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;
你知道造成这种差异的原因吗?构造函数什么时候可以扔?
最佳答案
对于构造函数
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
会阻止库包含测试来帮助用户发现代码中的错误(当然是在 Debug模式下)。 (有关更多信息,请参阅 Can std::string::compare(const char*) throw an exception?。)另一方面,UDL 运算符
constexpr std::string_view operator "" sv(const char* str, std::size_t len) noexcept;
通常在翻译文字时由语言调用:
using std::string_literals;
auto sv = "foo"sv;
不存在传入无效指针值的可能性,因此运算符为
noexcept
.当然,您可以直接使用无效值调用运算符,但这不是标准库应该处理的那种问题。
关于c++ - std::string_view 的 noexcept 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62061364/