Issue
class MyClass {
public:
int obj_field;
MyClass(int val) : obj_field(val) {}
void myMethod() {
static int my_static_var = obj_field; // <--- Why is this okay?
// ...
}
};
I was in depth convinced this is wrong and should not compile because I was sure they can only be initialized to constexpr (assuming values are initialized before the execution begins). To my surprise, it compiles no errors with gcc 9.4.0, C++17. Would it be able to postpone the initialization of the static variable till the first call or undefined behavior is more likely?
I understand that if it would ever work, static value will probably be picked from the first object that called the method.
Solution
Would it be able to postpone the initialization of the static variable till the first call
That is in fact the point when a local static variable is initialized. More specifically, initialization happens when the execution reaches the point of declaration for the first time.
or undefined behavior is more likely?
There's no UB in the example.
Why gcc accepts initializing the static variable within the method to the field of the object?
Because doing so is well formed.
Answered By - eerorika Answer Checked By - Marilyn (WPSolving Volunteer)