C++ Logo

std-proposals

Advanced search

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

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Thu, 24 Feb 2022 21:23:47 -0500
On Thu, Feb 24, 2022 at 6:40 PM organicoman via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> Hmm,
> That means that tglhe following code will print nonsense.
>
> struct foo
> {
> foo()=delete;
> foo(int _a) : a(_a) { printf("foo%d\n",a);}
> };
>
> struct bar
> {
> bar()=delete;
> bar(foo f) { printf("bar%d\n",f.a);}
> };
>
> struct test
> {
> bar b;
> foo f;
> int a;
> test(): b(f), f(a), a(22) {}
> };
>
> int main()
> {
> test t;
> return 0;
> }
>
> So instead of receiving a compiler error of a default constructor deleted for both bar and foo, i will receive junk!!

That's what happens when you use an object before it gets initialized.

> I seldomly read the standard, but this situation was out of discussion for me, since i assumed that i will logically receive a compiler error, and constructing a dependency graph between the data members was not that difficult to figure out.
> Can anyone explain the logic behind this choice of the standard?

What choice exactly?

The choice of allowing you to specify members in the member
initialization list out of order from their order of initialization?
Honestly, I have no idea why that was ever legal. There's probably a
historical reason for it.

The choice of allowing you to access an object's name before its
initialization? That ship sailed in C.

Received on 2022-02-25 02:23:57