user3735658
user3735658

Reputation:

Is static_cast from base to derived considered "safe" in THIS particular context?

In a tree of polymorphic hierarchy objects, only the Root type instance has null _parent. I am using this method to fetch the root object of a particular tree node:

inline Root * root() {
    Object * r = this;
    while (r->_parent) r = r->_parent;
    return static_cast<Root *>(r);
}

I've been reading that static casting from base to derived is generally not considered safe, but what about my particular scenario, where a Root type can be identified by the null _parent?

Upvotes: 2

Views: 314

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275385

It is safe so long as your invariant holds. However invariants enforced over wide portions of large code bases rarely stay held.

At the least, I would insert a Assert(dynamic_cast<...>(...)) here, and at every location parent is modified, in an attempt to enforce the invariant in debug.

Another approach would be to expose virtual Root* as_root() which only returns non-nullptr in Root. This is more expensive than (most) static_casts, but places the cast logic in a central searchable spot. It is rarely the case that such a virtual call is your program's bottleneck.

The more interesting thing is 'what do you do if you do not find a Root? Return nullptr probably, which means handling it at all call sites, at least at the level of Asserting in debug. If call sites are presumed not to handle it, return a Root& instead, and have failure call terminate/exit (after Assert) in debug (or release if you check it there, after logging/notifying/etc).

Upvotes: 2

jakobbotsch
jakobbotsch

Reputation: 6337

If you know that r is of type Root, then a static cast is completely safe. In fact, the only reason the compiler allows you to use static_cast in this context is because Root and Object are compatible. If you try it with two incompatible types, it yields a compiler error - a reinterpret_cast is needed in that case.

Upvotes: 1

Related Questions