Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refactoring code to use Boost shared pointers

I wrote a project using normal pointers and now I'm fed up with manual memory management.

What are the issues that one could anticipate during refactoring?

Until now, I already spent an hour replacing X* with shared_ptr<X> for types I want to automatically manage memory. Then I changed dynamic_cast to dynamic_pointer_cast. I still see many more errors (comparing with NULL, passing this to a function).

I know the question is a bit vague and subjective, but I think I can benefit from experience of someone who has already done this.

Are there some pitfalls?

like image 990
Abhishek Anand Avatar asked Dec 20 '22 22:12

Abhishek Anand


1 Answers

Although it's easy to just use boost::shared_pointer everywhere, you should use the correct smart pointer as per ownership semantics.

In most cases, you will want to use std::unique_ptr by default, unless the ownership is shared among multiple object instances.

If you run into cyclical ownership problems, you can break up the cycles with boost::weak_ptr.

Also keep in mind that while passing shared_ptr's around, you should always pass them by const reference for performance reasons (avoids an atomic increment) unless you really want to confer ownership to a different entity.

like image 172
Klemens Baum Avatar answered Dec 24 '22 01:12

Klemens Baum