How to introduce boost :: shared_ptr into an existing (large) C ++ codebase?

I'm currently trying to fix some of the flaws in our code base by introducing the use of smart pointers. The code base is very large and interconnected, like a spider that had a lot of coffee.

I was wondering if people had tried before and what their approach was.

My first step was to typedef classes as shown below.

#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 understand that this will lead to a wealth of compilation areas such as

 CTObjectPtr i = NULL; 

Completely shut down if smart pointers are enabled.

I was wondering if there is anything that I could do at this early stage to reduce the mass of compilation errors, or, as I suspect, is just taking things on a case by case basis.

Cheers Rich

+6
c ++ boost refactoring shared-ptr
source share
4 answers

Do not do this: typedefs I mean.

Presumably the old code has at least a few calls to delete ? That, of course, would not work in the case of a smart pointer.

A smart pointer to certain things or not, i.e. chases a specific instance through a code base. Make it work, then move on. Good luck

+9
source share

Instead of trying to inject smart pointers everywhere, you can use the Boehm-Demers-Weiser garbage collector and leave your code base intact.

He will also take care of circular references.

+6
source share

There is no easy way to do this. As you know, boost::shared_ptr and standard pointers are not interchangeable. What you do here is refactoring code, and unfortunately refactoring is time consuming and can be very tedious.

As sdg says, typedef ing pointers for shared_ptr are not a good idea and just increase the amount of code you have to write.

First, I would define pointers that really need to be changed to shared_ptr s. Obviously, you do not want to change all pointers to shared_ptr s. Most of them would probably be better than std::auto_ptr or boost::scoped_ptr , and some would be better than boost::weak_ptr , and finally, some of them might be great as simple C-style pointers .

Just go through each pointer that you need to change one by one, find all the links to it and make the necessary settings (for example, deleting calls to delete ).

+3
source share

I would very much limit the introduction of shared_ptr to an existing large code base. If you really want to use smart pointers to correct errors, I suggest using pointers with a scope and, in addition, I would use refactoring code and create a clear property.

0
source share

All Articles