https://gcc.gnu.org/bugzilla/show_bug.cgi?id=110195
Jonathan Wakely <redi at gcc dot gnu.org> changed:
What |Removed |Added
----------------------------------------------------------------------------
Resolution|--- |INVALID
Status|UNCONFIRMED |RESOLVED
--- Comment #6 from Jonathan Wakely <redi at gcc dot gnu.org> ---
(In reply to jack from comment #2)
> (In reply to Andrew Pinski from comment #1)
> > Before C++20, Single{} didn't call the constructor so this behavior is
> > expected.
>
> Could you explain why it didn't call the constructor before c++20? C++
> standard rules or compiler make it this way?
The standard.
class Single
{
private:
Single() = default;
};
In C++17 Single is an aggregate, and Single{} is aggregate-initialization,
which initializes each member in turn, without calling a constructor. Since it
doesn't use the constructor, it doesn't matter if it's private.
In C++20 it's not an aggregate, so Single{} does value-initialization using the
constructor, which is private.
The C++17 rule is:
An aggregate is an array or a class (Clause 12) with
— no user-provided, explicit, or inherited constructors (15.1),
— no private or protected non-static data members (Clause 14),
— no virtual functions (13.3), and
— no virtual, private, or protected base classes (13.1).
The type above meets this definition. It has a user-declared constructor, but
not a user-provided constructor.
In C++20 the rule changed to:
An aggregate is an array or a class (Clause 11) with
— no user-declared or inherited constructors (11.4.5),
— no private or protected direct non-static data members (11.8),
— no private or protected direct base classes (11.8.3), and
— no virtual functions (11.7.3) or virtual base classes (11.7.2).
Now the user-declared constructor means it's not an aggregate.
For the other classes:
class Single
{
private:
explicit Single() = default;
};
Not an aggregate in any version of C++ because it has an explicit user-declared
constructor.
class Single
{
private:
Single() {}
};
Not an aggregate in any version of C++ because it has a user-provided
constructor.
class Single
{
private:
Single() = default;
int a;
};
Not an aggregate in any version of C++ because it has a private member.
In all these cases the type is not an aggregate, so Single{} always does
value-initialization and always uses the constructor.
GCC is doing exactly what the standard requires.