Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Are these three default constructors equivalent in C++?

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++?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading