相关疑难解决方法(0)

为什么std :: unique_ptr operator*throw和operator->不抛出?

在C++标准草案(N3485)中,它声明如下:

20.7.1.2.4 unique_ptr观察者[unique.ptr.single.observers]

typename add_lvalue_reference<T>::type operator*() const;

1 Requires: get() != nullptr.
2 Returns: *get().

pointer operator->() const noexcept;

3 Requires: get() != nullptr.
4 Returns: get().
5 Note: use typically requires that T be a complete type.
Run Code Online (Sandbox Code Playgroud)

您可以看到operator*(取消引用)未指定为noexcept,可能是因为它可能导致段错误,但随后operator->在同一对象上指定为noexcept.两者的要求相同,但异常规范存在差异.

我注意到它们有不同的返回类型,一个返回一个指针,另一个返回一个引用.这是说operator->实际上没有取消引用任何东西吗?

事实是在operator->任何类型的指针上使用NULL,将是段错误(是UB).那么,为什么其中一个被指定为noexcept另一个而不是?

我确定我忽视了一些事情.

编辑:

看着std::shared_ptr我们有这个:

20.7.2.2.5 shared_ptr观察者[util.smartptr.shared.obs]

T& operator*() const noexcept;

T* operator->() const noexcept;
Run Code Online (Sandbox Code Playgroud)

这是不一样的?这与不同的所有权语义有什么关系吗?

c++ language-lawyer c++11

34
推荐指数
1
解决办法
3912
查看次数

标签 统计

c++ ×1

c++11 ×1

language-lawyer ×1