为何unique_ptr的operator*未标记为noexcept?
unique_ptr::operator*() marked noexcept? Great question! This is one of those subtle C++ standard details that looks odd at first glance, but makes sense once you dig into the reasoning. Let's break it down:
The standard uses conditional
noexcept
The C++ standard specifies thatunique_ptr<T>::operator*()has a conditional exception specification:noexcept(noexcept(*std::declval<T*>())). In plain terms, this means the operator isnoexceptonly if dereferencing a rawT*pointer is itselfnoexcept.For nearly all practical types (built-ins like
int, or regular user-defined classes), dereferencing a validT*is a pure memory access with zero chance of throwing. So in real-world use, this conditional spec acts exactly like an unconditionalnoexcept—it just follows the standard's formal approach to tying exception safety to the underlying expression.Why not make it unconditional?
The committee chose this conditional path for a few key reasons:- Future-proofing: While dereferencing a pointer can't throw today, the standard avoids hardcoding absolute guarantees that might limit future language extensions.
- Consistency:
shared_ptr<T>::operator*()uses the same conditionalnoexceptrule, keeping the smart pointer interface consistent across the standard library. - Formal correctness: The wording aligns with how other template operations specify exception safety—tying the behavior directly to the core expression (
*T*) rather than making a blanket assumption.
What does this mean for your hobby OS implementation?
If you're writing your own standard library for a hobby OS, markingoperator*()as unconditionallynoexceptis totally safe. Dereferencing a valid pointer never throws, and dereferencing a null pointer is undefined behavior (whichnoexceptdoesn't need to handle). Many production implementations effectively treat this as an unconditional guarantee anyway.
内容的提问来源于stack exchange,提问作者Thalhammer

