In the C++ standard draft (N3485), it states the following:
20.7.1.2.4 unique_ptr observers [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.
You can see that operator*
(dereference) is not specified as noexcept
, probably because it can cause a segfault, but then operator->
on the same object is specified as noexcept
. The requirements for both are the same, however there is a difference in exception specification.
I have noticed they have different return types, one returns a pointer and the other a reference. Is that saying that operator->
doesn't actually dereference anything?
The fact of the matter is that using operator->
on a pointer of any kind which is NULL, will segfault (is UB). Why then, is one of these specified as noexcept
and the other not?
I'm sure I've overlooked something.
EDIT:
Looking at std::shared_ptr
we have this:
20.7.2.2.5 shared_ptr observers [util.smartptr.shared.obs]
T& operator*() const noexcept;
T* operator->() const noexcept;
It's not the same? Does that have anything to do with the different ownership semantics?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…