Take these two classes for instance:
struct Owned {
Owned() : i() { }
void print() { cout << ++i << endl; }
int i;
};
struct Owner {
Owner(Owned& o) : o(o) { }
Owned& o;
~Owner() { o.print(); }
};
Is it dangerous to use them in this way?
int main() {
Owned owned;
Owner owner(owned);
}
It seems that, depending on the order in which they are destructed, that this could cause the destructor of owner to call a function on a destroyed owned. Is the order of destruction of local variables defined, and how can you make a situation where two instances refer to each other work?
Forgive me if this is common knowledge, I haven’t read anything about it anywhere though.
Local variables are destroyed in the opposite order of being created. In your case, you’re fine, since
ownerwill always be destroyed beforeowned.§6.6 [stmt.jump] p2However, care has to be taken if you can reassign the owned member after construction.
Don’t have them access each other in their destructor. Or make clear who exactly gets destroyed first, maybe with a callback or flag that gets passed. Example:
This will ensure that both objects never reference a non-existent one.
Mutually referencing objects are very rare anyways.