Should = default constructor be noexcept?

If I make a constructor = default:

Object::Object() = default;

should I mark it as noexcept?

Object::Object() noexcept = default;
Last edited on
It is difficult to say this is an absolute, but generally, yes, the default constructor should be noexcept.

There could be an exception if, for example, members of the class have default constructors (or otherwise are initialized appropriate as members) where they could throw an exception. If the default constructor for a class is declared noexcept, but a member throws during construction, you're accepting the fact this will terminate the application. It should also generate a warning or static analysis comment at the least.

To be clear what I'm saying, consider
1
2
3
4
5
6
7
8
9
class A
{
 private:

 B b { 1 };
 public

 A() noexcept;
};


If the constructor of B taking an integer happens to throw, the noexcept guarantee is violated, termination will result.

Compilation with Clang 8 didn't warn me when B throws.

Neither did Microsoft 14.2 (VS 2019)

This also is that much of an issue, per se, because A itself isn't throwing.
Last edited on
The defaulted default constructor is implicitly non-throwing unless
- it would call potentially-throwing constructors (of base-class or member subobjects)
- you use some initializer that is potentially-throwing
Details:
https://en.cppreference.com/w/cpp/language/noexcept_spec
Last edited on
Topic archived. No new replies allowed.