Why does aggregate initialization not work anymore since C++20 if a constructor is explicitly defaulted or deleted?
Asked Answered
M

4

56

I'm migrating a C++ Visual Studio Project from VS2017 to VS2019.

I'm getting an error now, that didn't occur before, that can be reproduced with these few lines of code:

struct Foo
{
    Foo() = default;
    int bar;
};
auto test = Foo { 0 };

The error is

(6): error C2440: 'initializing': cannot convert from 'initializer list' to 'Foo'

(6): note: No constructor could take the source type, or constructor overload resolution was ambiguous

The project is compiled with /std:c++latest flag. I reproduced it on godbolt. If I switch it to /std:c++17, it compiles fine as before.

I tried to compile the same code with clang with -std=c++2a and got a similar error. Also, defaulting or deleting other constructors generates this error.

Apparently, some new C++20 features were added in VS2019 and I'm assuming the origin of this issue is described in https://en.cppreference.com/w/cpp/language/aggregate_initialization. There it says that an aggregate can be a struct that (among other criteria) has

  • no user-provided, inherited, or explicit constructors (explicitly defaulted or deleted constructors are allowed) (since C++17) (until C++20)
  • no user-declared or inherited constructors (since C++20)

Note that the part in parentheses "explicitly defaulted or deleted constructors are allowed" was dropped and that "user-provided" changed to "user-declared".

So my first question is, am I right assuming that this change in the standard is the reason why my code compiled before but does not anymore?

Of course, it's easy to fix this: Just remove the explicitly defaulted constructors.

However, I have explicitly defaulted and deleted very many constructors in all of my projects because I found it was a good habit to make code much more expressive this way because it simply results in fewer surprises than with implicitly defaulted or deleted constructors. With this change however, this doesn't seem like such a good habit anymore...

So my actual question is: What is the reasoning behind this change from C++17 to C++20? Was this break of backwards compatibility made on purpose? Was there some trade off like "Ok, we're breaking backwards compatibility here, but it's for the greater good."? What is this greater good?

Mythos answered 30/7, 2019 at 12:12 Comment(4)
This is the paper. I don't find the rationale (which IMO boils down to "OMG these contrived examples are so surprising they must be fixed") persuasive. YMMV.Jagannath
I'd still consider it a good habit, I'd rather consider aggregate initialisation a bad habit...Highpressure
To answer the less-important first question, explicitly defaulted constructors are considered to be user-declared, but not user-provided. Thus, the change in wording there is indeed the reason for the new errors. (As a note, the standard falters a little in regards to the term "user-declared", by not properly defining it. It's roughly used as a counterpart to "implicitly-declared", though, which (when combined with the term itself) is enough to, ahem, implicitly define it.)Shayna
If one define some constructors, he expect that all objects are initialized with those constructors… so I consider this a welcome fix to the standard.Evensong
S
36

The abstract from P1008, the proposal that led to the change:

C++ currently allows some types with user-declared constructors to be initialized via aggregate initialization, bypassing those constructors. The result is code that is surprising, confusing, and buggy. This paper proposes a fix that makes initialization semantics in C++ safer, more uniform,and easier to teach. We also discuss the breaking changes that this fix introduces.

One of the examples they give is the following.

struct X {
  int i{4};
  X() = default;
};

int main() {
  X x1(3); // ill-formed - no matching c’tor
  X x2{3}; // compiles!
}

To me, it's quite clear that the proposed changes are worth the backwards-incompatibility they bear. And indeed, it doesn't seem to be good practice anymore to = default aggregate default constructors.

Straightlaced answered 30/7, 2019 at 12:24 Comment(4)
Shouldn't it be X x2{3} instead – or comma instead of semicolon after first variable? Apart from, I do consider it good practice to default the constructors, I rather consider aggregate initialisation bad practice (which we now can prevent this way).Highpressure
@Aconcagua, why do you think that aggregate initialisation is bad practice?Brame
@PatrickFromberg For aggregate initialisation, you rely on member order as we do not have designated initialisers (yet, at least) as we have in C. Imagine you need to add a new member, and for alignment or other reasons you need to place it in between some others. That will break aggregate initialisation. Constructors can be fixed appropriately, in contrast, so they are just safer.Highpressure
@Jagannath Really? Would you mind providing some reference? Bad fault, though, in my eyes...Highpressure
W
33

The reasoning from P1008 (PDF) can be best understood from two directions:

  1. If you sat a relatively new C++ programmer down in front of a class definition and ask "is this an aggregate", would they be correct?

The common conception of an aggregate is "a class with no constructors". If Typename() = default; is in a class definition, most people will see that as having a constructor. It will behave like the standard default constructor, but the type still has one. That is the broad conception of the idea from many users.

An aggregate is supposed to be a class of pure data, able to have any member assume any value it is given. From that perspective, you have no business giving it constructors of any kind, even if you defaulted them. Which brings us to the next reasoning:

  1. If my class fulfills the requirements of an aggregate, but I don't want it to be an aggregate, how do I do that?

The most obvious answer would be to = default the default constructor, because I'm probably someone from group #1. Obviously, that doesn't work.

Pre-C++20, your options are to give the class some other constructor or to implement one of the special member functions. Neither of these options are palatable, because (by definition) it's not something you actually need to implement; you're just doing it to make some side effect happen.

Post-C++20, the obvious answer works.

By changing the rules in such a way, it makes the difference between an aggregate and non-aggregate visible. Aggregates have no constructors; so if you want a type to be an aggregate, you don't give it constructors.

Oh, and here's a fun fact: pre-C++20, this is an aggregate:

class Agg
{
  Agg() = default;
};

Note that the defaulted constructor is private, so only people with private access to Agg can call it... unless they use Agg{}, bypasses the constructor and is perfectly legal.

The clear intent of this class is to create a class which can be copied around, but can only get its initial construction from those with private access. This allows forwarding of access controls, as only code which was given an Agg can call functions that take Agg as a parameter. And only code with access to Agg can create one.

Or at least, that's how it is supposed to be.

Now you could fix this more targetedly by saying that it's an aggregate if the defaulted/deleted constructors are not publicly declared. But that feels even more in-congruent; sometimes, a class with a visibly declared constructor is an aggregate and sometimes it isn't, depending on where that visibly declared constructor is.

Warren answered 30/7, 2019 at 13:0 Comment(8)
I see... ok, some convincing arguments here, thanks. Your last example would be even better, if you changed = default to = delete as this even more expresses the intent (and Agg{} still worked in C++17, uff... was not aware of that).Mythos
@sebrockm: Not really. If you delete the default constructor, then nobody is supposed to be able to create an object of that type (outside of copying). If you make it a private, defaulted constructor, then only people with private access should be able to create one (again, outside of copying).Warren
right, slightly different intent. Still, "nobody is supposed to create it (but still everyone can)" is an even more convincing argument than "only some chosen ones are supposed to create it (but still everyone can)". That was my point :)Mythos
@sebrockm: But that's easily countered by the argument, "If nobody is supposed to be able to create the object... why does the type exist at all?" And while you can point to various metaprogramming tools which use types purely as engines of computation, none of them actively forbid creating instances of such types, nor are they conceptually broken if someone does so. So why is it important to be able to create a type that cannot be instantiated, rather than just a type where instantiation isn't useful?Warren
I think we are talking about different things here. I'm not proposing the deletion of the default c'tor and thus expressing "this shall never be created" is a reasonable thing to do. Still, if I did that, I'd expect that absolutely never there will be an instance of this class. But contrary, everybody can create it. To me, that behavior is even a little more counter intuitive than your example where you do expect objects get created (just who can do it, is a surprise, but not that it can be done at all).Mythos
My point is that, if it's not a thing worth doing, who cares whether it can be done or not? It's not worth making a change to the standard to permit people to do useless things. Motivations for standard changes have to come from the perspective of making the language more useful; the strongest argument for a feature is an argument from utility, not consistency.Warren
I understand and I absolutely agree! Still, the "surprise-factor" is bigger for me, even if the origin of this surprise is doing something stupid in the first place (and thus shouldn't be motivation for a standard change).Mythos
bottom line/TLDR; aggregate initialization is broken in +17 and should be avoided for anything with methods of any kind as a matter of disciplineCleavable
M
15

Towards a less surprising aggregate in C++20

To be on the same page with all readers, lets start by mentioning that aggregate class types make up a special family of class types that can be, particularly, initialized by means of aggregate initialization, using direct-list-init or copy-list-init, T aggr_obj{arg1, arg2, ...} and T aggr_obj = {arg1, arg2, ...}, respectively.

The rules governing whether a class is an aggregate or not are not entirely straight-forward, particularly as the rules have been changing between different releases of the C++ standard. In this post we’ll go over these rules and how they have changed over the standard release from C++11 through C++20.

Before we visit the relevant standard passages, consider the implementation of the following contrived class type:

namespace detail {
template <int N>
struct NumberImpl final {
    const int value{N};
    // Factory method for NumberImpl<N> wrapping non-type
    // template parameter 'N' as data member 'value'.
    static const NumberImpl& get() {
        static constexpr NumberImpl number{};
        return number;
    }

private:
    NumberImpl() = default;
    NumberImpl(int) = delete;
    NumberImpl(const NumberImpl&) = delete;
    NumberImpl(NumberImpl&&) = delete;
    NumberImpl& operator=(const NumberImpl&) = delete;
    NumberImpl& operator=(NumberImpl&&) = delete;
};
}  // namespace detail

// Intended public API.
template <int N>
using Number = detail::NumberImpl<N>;

where the design intent has been to create a non-copyable, non-movable singleton class template which wraps its single non-type template parameter into a public constant data member, and where the singleton object for each instantiation is the only that can ever be created for this particular class specialization. The author has defined an alias template Number solely to prohibit users of the API to explicitly specialize the underlying detail::NumberImpl class template.

Ignoring the actual usefulness (or, rather, uselessness) of this class template, have the author correctly implemented its design intent? Or, in other words, given the function wrappedValueIsN below, used as an acceptance test for the design of the publicly intended Number alias template, will the function always return true?

template <int N>
bool wrappedValueIsN(const Number<N>& num) {
    // Always 'true', by design of the 'NumberImpl' class?
    return N == num.value;
}

We will answer this question assuming that no user abuses the interface by specializing the semantically hidden detail::NumberImpl, in which case the answer is:

  • C++11: Yes
  • C++14: No
  • C++17: No
  • C++20: Yes

The key difference is that the class template detail::NumberImpl (for any non-explicit specialization of it) is an aggregate in C++14 and C++17, whereas it is not an aggregate in C++11 and C++20. As covered above, initialization of an object using direct-list-init or copy-list-init will result in aggregate initialization if the object is of an aggregate type. Thus, what may look like value-initialization (e.g. Number<1> n{} here)—which we may expect will have the effect of zero-initialization followed by default-initialization as a user-declared but not user-provided default constructer exists—or direct-initialization (e.g. Number<1>n{2} here) of a class type object will actually bypass any constructors, even deleted ones, if the class type is an aggregate.

struct NonConstructible {
    NonConstructible() = delete;
    NonConstructible(const NonConstructible&) = delete;
    NonConstructible(NonConstructible&&) = delete;
};

int main() {
    //NonConstructible nc;  // error: call to deleted constructor

    // Aggregate initialization (and thus accepted) in
    // C++11, C++14 and C++17.
    // Rejected in C++20 (error: call to deleted constructor).
    NonConstructible nc{};
}

Thus, we can fail the wrappedValueIsN acceptance test in C++14 and C++17 by bypassing the private and deleted user-declared constructors of detail::NumberImpl by means of aggregate initialization, specifically where we explicitly provide a value for the single value member thus overriding the designated member initializer (... value{N};) that otherwise sets its value to N.

constexpr bool expected_result{true};
const bool actual_result =
    wrappedValueIsN(Number<42>{41}); // false
                           // ^^^^ aggr. init. int C++14 and C++17.

Note that even if detail::NumberImpl were to declare a private and explicitly defaulted destructor (~NumberImpl() = default; with private access specifyer) we could still, at the cost of a memory leak, break the acceptance test by e.g. dynamically allocating (and never deleting) a detail::NumberImpl object using aggregate initialization (wrappedValueIsN(*(new Number<42>{41}))).

But why is detail::NumberImpl an aggregate in C++14 and C++17, and why is it not an aggregate in C++11 and C++20? We shall turn to the relevant standard passages for the different standard versions for an answer.

Aggregates in C++11

The rules governing whether a class is an aggregate or not is covered by [dcl.init.aggr]/1, where we refer to N3337 (C++11 + editorial fixes) for C++11 [emphasis mine]:

An aggregate is an array or a class (Clause [class]) with no user-provided constructors ([class.ctor]), no brace-or-equal-initializers for non-static data members ([class.mem]), no private or protected non-static data members (Clause [class.access]), no base classes (Clause [class.derived]), and no virtual functions ([class.virtual]).

The emphasized segments are the most relevant ones for the context of this answer.

User-provided functions

The detail::NumberImpl class does declare four constructors, such that it has four user-declared constructors, but it does not provide definitions for any of these constructors; it makes use of explicitly-defaulted and explicitly-deleted function definitions at the constructors’ first declarations, using the default and delete keywords, respectively.

As governed by [dcl.fct.def.default]/4, defining an explicitly-defaulted or explicitly-deleted function at its first declaration does not count as the function being user-provided [extract, emphasis mine]:

[…] A special member function is user-provided if it is user-declared and not explicitly defaulted or deleted on its first declaration. […]

Thus, the detail::NumberImpl fulfills the aggregate class requirement regarding having no user-provided constructors.

For the some additional aggregate confusion (which applies in C++11 through C++17), where the explicitly-defaulted definition is provided out-of-line, refer to my other answer here.

Designated member initializers

Albeit the detail::NumberImpl class has no user-provided constructors, it does use a brace-or-equal-initializer (commmonly referred to as a designated member initializer) for the single non-static data member value. This is the sole reason as to why the detail::NumberImpl class is not an aggregate in C++11.

Aggregates in C++14

For C++14, we once again turn to [dcl.init.aggr]/1, now referring to N4140 (C++14 + editorial fixes), which is nearly identical to the corresponding paragraph in C++11, except that the segment regarding brace-or-equal-initializers has been removed [emphasis mine]:

An aggregate is an array or a class (Clause [class]) with no user-provided constructors ([class.ctor]), no private or protected non-static data members (Clause [class.access]), no base classes (Clause [class.derived]), and no virtual functions ([class.virtual]).

Thus, the detail::NumberImpl class fulfills the rules for it to be an aggregate in C++14, thus allowing circumventing all private, defaulted or deleted user-declared constructors by means of aggregate initialization.

We will get back to the consistently emphasized segment regarding user-provided constructors once we reach C++20 in a minute, but we shall first visit some explicit puzzlement in C++17.

Aggregates in C++17

True to its form, the aggregate once again changed in C++17, now allowing an aggregate to derive publicly from a base class, with some restrictions, as well as prohibiting explicit constructors for aggregates. [dcl.init.aggr]/1 from N4659 ((March 2017 post-Kona working draft/C++17 DIS), states [emphasis mine]:

An aggregate is an array or a class with

  • (1.1) no user-provided, explicit, or inherited constructors ([class.ctor]),
  • (1.2) no private or protected non-static data members (Clause [class.access]),
  • (1.3) no virtual functions, and
  • (1.4) no virtual, private, or protected base classes ([class.mi]).

The segment in about explicit is interesting in the context of this post, as we may further increase the aggregate cross-standard-releases volatility by changing the declaration of the private user-declared explicitly-defaulted default constructor of detail::NumberImpl from:

template <int N>
struct NumberImpl final {
    // ...
private:
    NumberImpl() = default;
    // ...
};

to

template <int N>
struct NumberImpl final {
    // ...
private:
    explicit NumberImpl() = default;
    // ...
};

with the effect that detail::NumberImpl is no longer an aggregate in C++17, whilst still being an aggregate in C++14. Denote this example as (*). Apart from copy-list-initialization with an empty braced-init-list (see more details in my other answer here):

struct Foo {
    virtual void fooIsNeverAnAggregate() const {};
    explicit Foo() {}
};

void foo(Foo) {}

int main() {
    Foo f1{};    // OK: direct-list-initialization

    // Error: converting to 'Foo' from initializer
    // list would use explicit constructor 'Foo::Foo()'
    Foo f2 = {};
    foo({});
}

the case shown in (*) is the only situation where explicit actually has an effect on a default constructor with no parameters.

Aggregates in C++20

As of C++20, particularly due to the implementation of P1008R1 (Prohibit aggregates with user-declared constructors) most of the frequently surprising aggregate behaviour covered above has been addressed, specifically by no longer allowing aggregates to have user-declared constructors, a stricter requirement for a class to be an aggregate than just prohibiting user-provided constructors. We once again turn to [dcl.init.aggr]/1, now referring to N4861 (March 2020 post-Prague working draft/C++20 DIS), which states [emphasis mine]:

An aggregate is an array or a class ([class]) with

  • (1.1) no user-declared, or inherited constructors ([class.ctor]),
  • (1.2) no private or protected non-static data members ([class.access]),
  • (1.3) no virtual functions ([class.virtual]), and
  • (1.4) no virtual, private, or protected base classes ([class.mi]).

We may also note that the segment about explicit constructors has been removed, now redundant as we cannot mark a constructor as explicit if we may not even declare it.

Avoiding aggregate surprises

All the examples above relied on class types with public non-static data members, which is commonly considered an anti-pattern for the design of “non-POD-like” classes. As a rule of thumb, if you’d like to avoid designing a class that is unintentionally an aggregate, simply make sure that at least one (typically even all) of its non-static data members is private (/protected). For cases where this for some reason cannot be applied, and where you still don’t want the class to be an aggregate, make sure to turn to the relevant rules for the respective standard (as listed above) to avoid writing a class that is not portable w.r.t. being an aggregate or not over different C++ standard versions.

Michele answered 28/9, 2020 at 19:9 Comment(1)
class avoid_aggregate; explicit none_aggregate::none_aggregate(avoid_aggregate);Housley
Q
4

Actually, MSDN addressed your concern in the below document:

Modified specification of aggregate type

In Visual Studio 2019, under /std:c++latest, a class with any user-declared constructor (for example, including a constructor declared = default or = delete) isn't an aggregate. Previously, only user-provided constructors would disqualify a class from being an aggregate. This change puts additional restrictions on how such types can be initialized.

Quiteris answered 30/7, 2019 at 12:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.