Suppose there is a hierarchy of two classes (class Derived: public Base
). Both these classes have big memory footprint and costly constructors. Note that nothing in these classes is allocated in heap: they just have a big sizeof
.
Then there is a function with a fast path (executed always) and a slow path (executed conditionally). Fast path needs a Base
instance, and slow path needs a Derived
instance constructed from existing base. Also, slow path decision can be made only after the fast path.
Current code looks like this:
void f()
{
Base base;
/* fast path */
if (need_slow_path) {
Derived derived (base);
/* slow path */
}
}
This is inefficient, because the base needs to be copied into derived; also the base is allocated twice and there is a risk of overflowing the stack. What I want to have:
- allocate memory for
Derived
instance - call
Base
ctor on it - execute the fast path
- if needed, call
Derived
ctor on the existingBase
instance and execute the slow path
Is it possible in C++? If not, what are possible workarounds? Obviously, I'm trying to optimize for speed.