Reputation: 14603
Defaulted default constructors are generated by the C++
compiler, the user has no control over them. Can they throw? Is it ok to specify noexcept
when declaring one?
The following code compiles fine with gcc
.
struct A
{
A() = default;
};
struct B
{
B() noexcept = default;
};
int main()
{
A a;
B b;
return 0;
}
Upvotes: 6
Views: 479
Reputation: 59831
It is allowed to add a noexcept
specifier to a defaulted special member function (default constructor, copy-constructor, assignment-operator etc.).
A default
declared special member function will have a noexcept
specifier depending on the noexcept
specifiers of the involved functions (its implicit noexcept specifier). If you explicitly specify noexcept
compilation should fail if this conflicts with the implicit noexcept
specifier.
Upvotes: 8
Reputation: 227468
can default constructors throw?
Yes, they can. For example, if the class has data member(s) whose default constructor throws.
struct Foo
{
Foo() { /* throws */}
};
struct Bar
{
Bar() = default;
Foo f;
}
Upvotes: 5