noexcept Specifier
Marking functions as non-throwing
Interview Relevant: Modern C++ practice
noexcept Specifier
Declare that a function doesn't throw exceptions.
Code Examples
Using noexcept for exception specification.
cpp
1// noexcept - function won't throw
2void safeFunction() noexcept {
3 // If exception escapes, terminate() is called
4}
5
6// Conditional noexcept
7template<typename T>
8void swap(T& a, T& b) noexcept(noexcept(T(move(a)))) {
9 T temp = move(a);
10 a = move(b);
11 b = move(temp);
12}
13
14// noexcept operator - check if expression can throw
15static_assert(noexcept(1 + 1)); // true
16static_assert(!noexcept(throw 1)); // true
17
18// Move constructor should be noexcept
19class Resource {
20public:
21 Resource(Resource&& other) noexcept
22 : data(other.data) {
23 other.data = nullptr;
24 }
25};
26
27// STL containers use noexcept to decide
28// whether to move or copy during reallocation
29// vector will only move if move ctor is noexcept
30
31// Destructor is implicitly noexcept
32~MyClass() { // noexcept by default
33 // Don't throw from destructors!
34}