I had to work on a legacy C++ code base that doesn’t use smart pointers, everything is instead tracked by plain pointers. The original reasons for that include downright crappy compiler and just the code being quite old. Nowadays, I don’t see anything preventing the use of smart pointers in the legacy code base.
The question is, how do you transition from plain pointers to smart pointers when you have a big code base that cannot be updated over night.
I’ll present some techniques in this post. You can also check out my video on the same topic.
Example
Let’s suppose the code looks roughly like this:
(The actual legacy code base looks much worse, but let’s focus on the pointer business.)
bool createDestroyable(Destroyable *& destroyableOut)
{
destroyableOut = new Destroyable;
if ( !destroyableOut->init() )
{
destroyableOut->destroy();
destroyableOut = NULL;
return false;
}
return true;
}
bool legacy()
{
Destroyable * ptr = NULL;
bool rc = createDestroyable( ptr);
rc = rc && ptr->doStuff();
if (ptr != NULL)
{
ptr->destroy();
}
return rc;
}
And that’s just an example, there are many functions like createDestroyable() and even more call sites, so it is impossible to change the signature of createDestroyable() and update all call sites in one go.
Continue reading “Gluing Smart Pointers to Legacy Code”