(C++) noexcept
April 2, 2018 ยท View on GitHub
noexcept is a keyword to indicate that a function may not throw an exception. If the function does throw an exception, std::terminate is called.
Example
Advice
- If a function may not throw, declare it noexcept [1]
- Generated destructors are implicitly noexcept, as destructors should not throw [2]
- A generated copy or move operation is implicitly noexcept if all of the copy or move operations it uses on members of its class have noexcept destructors [3]. Declare a move operation noexcept, as it should not throw [3]
- Reserve noexcept for functions with wide interfaces [4]
- noexcept matters [5]
References
- [1] Bjarne Stroustrup. The C++ Programming Language (4th edition). 2013. ISBN: 978-0-321-56384-2. Chapter 13.7. Advice, page 387: '[23] If your function may not throw, declare it noexcept'
- [2] Bjarne Stroustrup's C++11 FAQ: 'A destructor shouldn't throw; a generated destructor is implicitly noexcept (independently of what code is in its body) if all of the members of its class have noexcept destructors.'
- [3] Bjarne Stroustrup's C++11 FAQ: 'It is typically a bad idea to have a move operation throw, so declare those noexcept whereever possible. A generated copy or move operation is implicitly noexcept if all of the copy or move operations it uses on members of its class have noexcept destructors.'
- [4] Scott Meyers. C++ And Beyond 2012 session: 'Initial thoughts on Effective C++11'. 2012. 'Reserve noexcept for Functions with Wide Interfaces'
- [5] Jason Turner. C++ Weekly - Ep 109 - When noexcept Really Matters