<span>noexcept</span> is a keyword introduced in C++11, used to specify that a function will not throw exceptions. It serves as both a specifier and an operator, playing an important role in performance optimization, code safety, and compiler optimization.
1. <span><span>noexcept</span></span> Basic Usage
1. As a Function Specifier
void my_function() noexcept { // This function promises not to throw exceptions}
Equivalent to:
void my_function() noexcept(true); // Explicitly indicates it will not throw
If written as
void my_function() noexcept(false) { // May throw exceptions}
2. <span><span>What is the Use of noexcept</span></span>?
1. Performance Optimization: Enables More Efficient Code Paths
Some standard library functions (such as <span>std::vector::resize</span>, <span>std::swap</span>) choose more efficient implementations when determining if the element type has a <span>noexcept</span> move constructor.
<span>std::vector</span>‘s <span>push_back</span> and <span>noexcept</span>
#include <vector>
#include <iostream>
struct MayThrow { MayThrow(MayThrow&&) { /* May throw exceptions */ }
MayThrow&& operator=(MayThrow&&) { return *this; }};
struct NoThrow { NoThrow(NoThrow&&) noexcept { /* Will not throw */ std::cout << "Moving NoThrow\n"; }
NoThrow&& operator=(NoThrow&&) noexcept { return *this; }};
int main() { std::vector<NoThrow> v1; v1.push_back(NoThrow{}); // Can safely use move constructor std::vector<MayThrow> v2; v2.push_back(MayThrow{}); // If move constructor may throw, vector may use copy constructor to ensure exception safety}
If your type supports a <span>noexcept move constructor</span>, <span>std::vector</span> can directly move elements when reallocating memory instead of conservatively copying, resulting in better performance.
2. Exception Safety Guarantee
<span>noexcept</span> is a contract: this function will not throw exceptions.
If a function declared as <span>noexcept</span> actually throws an exception, the program will directly call <span>std::terminate()</span>, terminating immediately.
void func() noexcept { throw std::runtime_error("oops"); // Directly terminates the program!}
int main() { func(); // Program crashes, no stack unwinding}
This is intentionally designed in some system-level codeāto avoid the uncertainty and overhead of handling exceptions on critical paths.
3. Helps Compiler Optimization
When the compiler knows a function will not throw exceptions, it can:
- Remove exception handling stack unwinding code
- Reduce the size of the generated binary
- Increase the likelihood of inlining
- Optimize register allocation
void fast_func() noexcept { // The compiler knows this won't throw exceptions, can optimize aggressively for (int i = 0; i < 1000; ++i) { // ... }}