c++ - std::string_view 的 noexcept 构造函数

标签 c++ c++17 noexcept user-defined-literals string-view

根据 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 (即,接受所有输入),并且未标记 noexceptN3279 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/

相关文章:

c++ - 使用 std::Optional 而不是自己的结构

c++ - 函数 typedefs 中的 noexcept 说明符

c++ - 不支持 vector 的 noexcept 要求

.net - 使用/clr 编译时使用 boost 线程

c++ - 使用 OpenCV 进行激光线检测

c++ - 为什么这会导致死锁?

c++ - 为什么 std::function::argument_type 已被弃用?

c++ - 将空指针传递给新位置

c++ - 从客户端应用程序调试动态库

c++ - 派生模板覆盖成员函数 C++ 的返回类型