vendredi 3 juin 2016

When is a private constructor not a private constructor?

Let's say I have a type and I want to make its default constructor private. I write the following:

class C {
    C() = default;
};

int main() {
    C c;           // error: C::C() is private within this context (g++)
                   // error: calling a private constructor of class 'C' (clang++)
                   // error C2248: 'C::C' cannot access private member declared in class 'C' (MSVC)
    auto c2 = C(); // error: as above
}

Great.

But then, the constructor turns out to not be as private as I thought it was:

class C {
    C() = default;
};

int main() {
    C c{};         // OK on all compilers
    auto c2 = C{}; // OK on all compilers
}    

This strikes me as very surprising, unexpected, and explicitly undesired behavior. Why is this OK?

Aucun commentaire:

Enregistrer un commentaire