4 ms·
struct A { int a; int b; A() : b(1), a(b) { } }; . Here, the b field is used uninitialized because the order of member initializers in the mem
by BruceEel 4y ago
struct A {
int a;
int b;
A() : b(1), a(b) { }
};
.
Here, the b field is used uninitialized because the order of member initializers in the member initializer list is irrelevant;
what matters is the order of declarations in the class definition.
(A related warning, -Wreorder, can be used to warn when the order of member initializers does not match the declaration order.)
I don't get it. Why b? Do they mean a?
- dundarious 4y agoThe order of initialization is the order of definition, i.e., a then b (because the definition order is `int a; int b;`). So initialization happens like so: // implicitly, a = undefined; // implicitly, b = undefined; a = b; b = 1; So b is used when its value is undefined. The undefined value is assigned to a.
- BruceEel 4y agoWhat confused me in their wording is that they seem to imply that the problem is: b would be left uninitialized, rather than: a depends on uninitialized b. Your explanation, OTOH, is straightforward to read.
- dundarious 4y agoUnderstandable. The original is correct that b is used uninitialized, but they don't clarify that it is a that is left uninitialized.
- tialaramex 4y agoMmm? The consequence of reading the uninitialized variable is that your program's behaviour is Undefined. There's no point worrying about this other variable named 'a', it's already game over. It's not called "Temporarily unusual" behaviour or "Reliably crashing" behaviour or even "I bet it'll probably just skip that and do the next thing" behaviour, it's Undefined for a reason.
- dundarious 4y agoThe distinction is helpful so that people properly understand what's going on with and what's wrong with the code in question (the context is helping someone who did not fully understand). You're talking about the consequences in terms of compiler output and code execution, and yes, the usage is the problem.
- nicoburns 4y agoSeems like that really ought to be made a compile error!
- vitus 4y agoIn this case, a is the first value to be initialized, but it's using the value of `b` (which is uninitialized).
- swatcoder 4y agoIt’s tricky wording. When they say “b is used uninitialized”, they’re referring to it’s usage in that snippet. It’s uninitialized when referenced as a value for “a”. It’s pretty easy to read that text as suggesting that b would be uninitialized in subsequent code, but that’s (not true, as you suspect, and) not what it’s talking about.