【发布时间】:2013-02-18 15:47:47
【问题描述】:
在 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.
可以看到operator*(取消引用)没有指定为noexcept,可能是因为它会导致segfault,但是随后同一个对象上的operator->被指定为noexcept。两者的要求相同,但异常规范有所不同。
我注意到它们有不同的返回类型,一个返回一个指针,另一个返回一个引用。那是说operator-> 实际上并没有取消引用任何东西吗?
事实上,在任何类型的 NULL 指针上使用 operator-> 都会出现段错误(是 UB)。那么,为什么其中一个被指定为noexcept 而另一个不是?
我确定我忽略了一些东西。
编辑:
看看std::shared_ptr,我们有这个:
20.7.2.2.5 shared_ptr 观察者 [util.smartptr.shared.obs]
T& operator*() const noexcept;
T* operator->() const noexcept;
不一样吗?这与不同的所有权语义有什么关系吗?
【问题讨论】:
-
"这是说 operator-> 实际上并没有取消引用任何东西?"是的,就是这样
-
也许是允许实现在选择时抛出空指针取消引用。
标签: c++ c++11 language-lawyer