Reputation: 19325
Much to my shame, I haven't had the chance to use smart pointers in actual development (the supervisior deems it too 'complex' and a waste of time). However, I planned to use them for my own stuff...
I have situations regarding de-initing a module after they are done, or when new data is loaded in. As I am using pointers, I find my code littered with check for null such as this...
// TODO: Reset all opened windows
// Deinit track result player
if (trackResultPlayer_)
trackResultPlayer_->reset();
// disconnect track result player
disconnect(trackResultPlayer_);
disconnect(trackResultAnimator_);
}
if (videoPlayerWindow_)
{
videoPlayerWindow_->reset();
// Disconnect the video player window from source movie data
disconnect(videoPlayerWindow_);
}
// Disconnect this module from its children as they would be connected again
disconnect(this);
If I am to use smart pointers, instead of raw pointers, how could this problem be alleviated?
Upvotes: 1
Views: 668
Reputation: 248229
Make each of your classes implement a destructor which performs all the cleanup/deinitialization you need for that class.
Create an instance of the class, and wrap it in a boost::shared_ptr
.
Then pass copies of that to every function which needs access to the instance.
And the smart pointer will ensure that once the object is no longer used (when all the shared pointers have been destroyed), the object they point to is destroyed. its destructor is run, and all the cleanup is executed.
As always in C++, use RAII whenever possible.
Whenever you have code like x.reset()
or disconnect(x)
, the first thing you should do is ask yourself "doesn't this belong in a destructor?"
Further, whenever you use x->y()
you should ask yourself:
Upvotes: 4
Reputation: 40869
Checks against NULL aren't a problem - and smart pointers don't meddle with that anyway.
Upvotes: 2
Reputation: 31061
Smart pointer are primarily an instrument to manage the memory being pointed to. They are not meant as something, which would free you from the burden of NULL value checking...
In you example code, I don't see much potential for smart pointers reducing the code complexity, unless you move calls like videoPlayerWindow_->reset()
, disconnect(videoPlayerWindow_)
and such into the destructor of the class, videoPlayerWindow
is an instance of.
Upvotes: 2