1

I stumbled upon a line of code in this question. It can be boiled down to

#include <iostream>
struct foo {
    int x;
    foo(int a) : x(a) {}
};

int main() {
    foo f(f.x);         // UB !!
    std::cout << f.x;
}

It compiles with a warning:

prog.cc:9:14: warning: 'f.foo::x' is used uninitialized in this function [-Wuninitialized]
     foo f(f.x);

Note that there is no such warning produced in the code from the question: https://wandbox.org/permlink/lNQWKWefobUtwD51

Now my question is two-fold. Sorry for putting two into one...

Why can we use f before it is even declared?

In foo f(f.x);, at which point is f declared? Isn't (f.x) part of the declaration? How is it possible that I can use the object as parameter to its constructor?

Next, I know that undefined behaviour is there for a reason, but I just cannot wrap my head around this case...

Why does C++ need to allow writing foo f(f.x);? Why can / should it not be an error?

I can imagine correct cases when the contructor takes a reference or a pointer and it is not used before f is fully constructed. However, f.x is passed by value and there is definitely no way f.x could have been initialized before it has been initialized.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185

0 Answers0