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;
}
A type with a public default constructor is Default Constructible; Do you want to learn how we define a Defaulted Default Constructor? In the definition of a default Constructor, class_name must name the current class or current instantiation of a class template.
The implicitly-declared (or defaulted on its first declaration) default constructor has an exception specification as described in dynamic exception specification (until C++17) exception specification (since C++17)
With the latter, the function becomes "user-provided". And that changes everything. If you attempt to default construct one, the compiler will generate a default constructor automatically. Same goes for copy/movement and destructing.
The default constructor for class T is trivial (i.e. performs no action) if all of the following is true: The constructor is not user-provided (i.e., is implicitly-defined or defaulted on its first declaration)
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With