Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constructor is implicitly deleted because its exception-specification does not match the implicit exception-specification

Tags:

c++

Can anyone explain me why using constructor marked as default will have the error but the other one doesn't have. My understanding is they are very much similar. Thanks.

class B {
public:
    B() {
        throw int(42);
    }
};

class A {
public:
    A() noexcept = default; // error: use of deleted function ‘A::A()’
                            // note: ‘A::A() noexcept’ is implicitly deleted because
                            // its exception-specification does not match the implicit exception-specification ‘’
    //A() noexcept : m_b{}{}
    B m_b;
};
like image 563
chuong vo Avatar asked Sep 20 '25 12:09

chuong vo


1 Answers

Originally, the declaration of the constructor was already ill-formed, the idea being that the defaulted function ought to behave identically to the implicit declaration. Your explicit implementation has no such restriction: noexcept functions are allowed to call potentially throwing functions, and the behavior is even well-defined if they throw.

In C++14 it was relaxed to be merely deleted in that case. Later it was realized that even that was too restrictive (and difficult to implement correctly), so it was relaxed again: now the exception specification can be anything (but there’s still an automatic one for defaulted functions).

Both of these changes were retroactive, so you’ll see a dependence on compiler version more than language version.

Note that none of this depends on the actual throw in B::B: that constructor is potentially throwing regardless.

like image 137
Davis Herring Avatar answered Sep 23 '25 03:09

Davis Herring