Consider the following code:
#include <type_traits>
template<typename T>
struct A1 {
T t;
// implicitly-declared default constructor
};
template<typename T>
struct A2 {
T t;
// explicitly-declared default constructor without noexcept
A2() = default;
};
template<typename T>
struct A3 {
T t;
// explicitly-declared default constructor with noexcept
A3() noexcept(std::is_nothrow_default_constructible<T>::value) = default;
};
Are these three default constructors equivalent in C++?
>Solution :
Are these three default constructors equivalent in C++?
Yes the default ctors are equivalent in the context of noexcept specification.
This can be seen from default ctor:
The implicitly-declared (or defaulted on its first declaration) default constructor has an exception specification as described in dynamic exception specification(until C++17) noexcept specification(since C++17).
So we move onto noexcept specification:
Every function in C++ is either non-throwing or potentially throwing:
- potentially-throwing functions are:
- functions declared without noexcept specifier except for
- default constructors, copy constructors, move constructors that are implicitly-declared or defaulted on their first declaration unless
- a constructor for a base or member that the implicit definition of the constructor would call is potentially-throwing (see below)