Example code:
struct Foo {
Foo() { instance = this; }
int value = 0;
static Foo * instance;
};
Foo * Foo::instance = nullptr;
int main(int argc, char * argv[]) {
Foo const foo;
//foo.value = 1; // Compiler error, as expected.
Foo::instance->value = 1; // Fine.
}
Here foo
is constant, but can be modified via the static instance
pointer, which is assigned the value of this
in Foo
's constructor. Setting aside questions of why one might want to do something like this, my understanding is that there's nothing here that's technically incorrect.
I was confident this was safe, but in this thread there seem to be some suggestions to the contrary. One person seems to describe a similar example as ill-formed, while someone else mentions undefined behavior.
Advisability aside, is this technically correct and safe? Or is there some issue I'm missing?