Site Tools


wiki:cpp-noexcept

Table of Contents

C++ noexcept

noexcept is a specifier declaring that a function will not throw exceptions (or will terminate if it does). A noexcept function enables compiler optimizations and is required for strong exception safety guarantees in moves and swaps. Misusing noexcept on code that can actually throw results in std::terminate.

Use noexcept on move constructors, move assignment, swaps, and other operations that standard containers rely on to be nothrow.

Example

This example shows noexcept enabling optimizations and required for move operations.

// compile: g++ -o noexcept noexcept.cpp
// run: ./noexcept
// description: noexcept enables optimizations and satisfies container requirements
 
#include <iostream>
#include <vector>
#include <utility>
 
class SafeBuffer {
private:
    int* data;
    size_t size;
public:
    SafeBuffer(size_t n) : size(n), data(new int[n]) {}
 
    ~SafeBuffer() { delete[] data; }
 
    SafeBuffer(SafeBuffer&& other) noexcept
        : data(other.data), size(other.size) {
        other.data = nullptr;
    }
 
    SafeBuffer& operator=(SafeBuffer&& other) noexcept {
        delete[] data;
        data = other.data;
        size = other.size;
        other.data = nullptr;
        return *this;
    }
};
 
int main() {
    std::vector<SafeBuffer> v;
    v.push_back(SafeBuffer(100));  // move is noexcept, vector optimizes
 
    return 0;
}
wiki/cpp-noexcept.md · Last modified: by 127.0.0.1