C++ noexcept | Exception Specifications and Optimization
이 글의 핵심
Use noexcept to document non-throwing operations and unlock vector reallocation and other optimizations safely.
What is noexcept?
noexcept states that a function does not throw exceptions. If it does anyway, std::terminate is invoked (typically).
void f() noexcept;
void g() noexcept(true); // same as noexcept
void h() noexcept(false); // may throw
Why use it?
- Enables optimizations (less unwind machinery assumed).
- Move operations on
std::vectorelements: if move is noexcept, reallocation can move; otherwise copies may be used for exception safety.
Conditional noexcept
template<typename T>
void swap(T& a, T& b) noexcept(noexcept(T(std::move(a)))) {
// ...
}
Destructors
Destructors are implicitly noexcept unless a base or member destructor is noexcept(false) (rules tightened over standards—verify for your version).
noexcept operator
static_assert(noexcept(f()));
Related posts
- Exception handling
- Move semantics
Keywords
C++, noexcept, exceptions, optimization, move constructor