skip to content
Ivan's wiki
Site Tools
Search
Tools
Show pagesource
Backlinks
Recent Changes
Media Manager
Sitemap
>
Recent Changes
Media Manager
Sitemap
cpp-noexcept
This page is read only. You can view the source, but not change it.
# C++ noexcept **[noexcept](https://en.cppreference.com/w/cpp/language/noexcept_spec)** 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. ```cpp // 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; } ```
Page Tools
Show pagesource
Backlinks
Back to top