How to introduce boost::shared_ptr into an existing (large) C++ codebase?
-
22-09-2019 - |
Question
I am currently trying to fix a few weaknesses in our code base by introducing the use of smart pointers. The code base is very large, and interlinked like a spider who's had one to many coffee's.
I was wondering if people had tried the before and what their approach was.
My first step has been to typedef classes, as follows.
#ifndef USE_SMART_POINTERS
#define USE_SMART_POINTERS 0
#endif
#if USE_SMART_POINTERS == 1
#include <boost/smart_ptr.hpp>
#endif
namespace ProductX
{
// forward decleration
class CTObject;
//typedefs
#if USE_SMART_POINTERS == 1
typedef boost::shared_ptr<CTObject> CTObjectPtr;
#else
typedef CTObject* CObjectPtr;
#endif
}
Now I realise this will lead to a wealth of compile areas, things like
CTObjectPtr i = NULL;
Will completly bork when smart pointers are enabled.
I was wondering if there was anything I could do at this early stage to reduce the mass of compile errors, or is it as I suspect just take things on a case by case basis.
Cheers Rich
Solution
Don't do this: the typedefs I mean.
Presumably the old code has at least some delete calls in it? Which would certainly fail in the case of a smart pointer.
Smart pointer certain things or not, i.e. chase a specific instance through the code base. Make it work, then move on. Good Luck!
OTHER TIPS
Instead of trying to introduce smart pointers everywhere you could use the Boehm-Demers-Weiser garbage collector and leave your code base intact.
It will also take care of cyclic references.
There is no easy way to do this. As you've found out, boost::shared_ptr
s and standard pointers are not interchangeable. What you are doing here is refactoring code, and unfortunately refactoring takes a long time and can be very tedious.
As sdg said, typedef
ing pointers for shared_ptr
s is not a good idea, and just increases the amount of code you have to write.
First, I would identify the pointers that actually need to be changed to shared_ptr
s. Obviously you don't want to be changing all pointers to shared_ptr
s. Most would probably be better off as std::auto_ptr
s or boost::scoped_ptr
s and some would be better as boost::weak_ptr
, and finally some might just be fine as plain C-style pointers.
Just go through each pointer that needs changing one-by-one, find all references to it, and make the necessary adjustments (e.g. removing calls to delete
).
I would be very restrictive in introducing shared_ptr into an existing large codebase. If you really want to use smart-pointers to fix errors I suggest using scoped pointers and other than that I would refactor code and design clear ownership.