lundi 9 novembre 2020

Use of `= default` allowing private constructor to be accessed

I have the code:

class Key
{
private:
    // If I use the = default keyword here, the line "Key a = {};" compiles
    // If I instead use Key() {}, that same line does not compile (as the constructor is private)
    Key() = default;

    Key(Key const &) = default;
    Key(Key &&) = default;

    Key & operator=(Key const &) = default;
    Key & operator=(Key &&) = default;
};

int main()
{
    // This line compiles when = default is used, but not when an empty constructor is used
    Key a = {};
    return 0;
}

What, specifically, is the difference between the default constructor and the empty constructor in this specific instance? Also, I would like for this to NOT compile, is explicitly writing my own empty constructor the only way to do so here? Note: This was tested with both GCC 8.3 and Clang 10.0 with identical results.

Aucun commentaire:

Enregistrer un commentaire