C++ Logo


Advanced search

Re: [std-proposals] Relax condition for potentially invoked destructor in constructor

From: Arvid Norberg <arvid.norberg_at_[hidden]>
Date: Fri, 25 Feb 2022 22:09:18 +0100
On Fri, Feb 25, 2022 at 8:45 PM organicoman via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> Also, if my compiler allows me to shuffle the initialization order of data
> members.
> For me, that is a strong guarantee that it will catch the following case
> and process it without error:
> Given the struct: base and derived above,
> struct mostDerived: public derived
> {
> int a;
> double d;
> mostDerived (): d(3.14), derived(), a(123){}
> };
> So logically, the compiler should help me here and make sure that this
> constructor produce correct code, right?

Assuming you mean "according to the standard" when you say "correct"; yes,
the compiler will produce correct code

The correct code is that "derived" is initialized first, then "a", then
"d". If you were hoping to have a different initialization order (as the
code suggests) you're in luck. All big compilers warn about this these days.

> Otherwise i need always to compile my constructor myself before my
> compiler does it. Which is not programming for me.
> So my proposal, or suggestion, is relaxing this ordering rule on data
> member initialization.
> But if this flexibility is not desired, and ppl are content with what they
> have, then it's ok.

I believe it's generally considered important to destruct objects in the
inverse order of construction. If you don't believe that is important, your
position is more understandable.

Keep in mind that the constructor(s) and destructors may be defined in
different translation units. The only chance they have to agree on the
initialization order is via the class definition (i.e. in the shared header
file). In theory, you could define a different order in the class
definition (there have been proposals to do this by controlling layout
separate from declaration order).

Arvid Norberg

Received on 2022-02-25 21:09:33