c++language-lawyer

Is it standard conformant to define static storage objects with cyclic references?


struct Object {
    Object* other;
};

//extern forward declarations
extern Object object_a;
extern Object object_b;

Object object_a = { &object_b };
Object object_b = { &object_a };

int main() {
    return 0;
}

This code compiles, but does it conform to the standard? Is there some issue with using extern forward declarations in order to define cyclic references in compile-time allocated/constructed objects?


Solution

  • I don't see a problem here.

    Both object_a and object_b are lvalues and have an address. Their other pointers are initialized according to static initialization rules with the address of the other object in each case. That other object may not be initialized when assigning the other member, but its (implicitly defined) constructor does not dereference the pointer, it just stores it.

    A more intricate case is showcased in the language reference, under Initialization / Deferred dynamic initialization.