Shared pointers hell

I just fixed a problem in my program which was causing a lot of runtime exceptions thanks to my ignorance on how to use the boost::shared_ptr class and I think is important to prevent people of going through the same. When I created or reset a shared pointer using the contents of other pointer this is what I did:

shared_ptr source(new int);
*source = 3;
// here begin my problems
shared_ptr
destination(source.get());
destination.reset(source.get());

So, what's wrong with the code here? Well, basically that in this way, since I was using the raw pointers, the counter (which is used to free the memory) is not updated which would lead to a double call to the destructor of the objects (which was exactly my problem). The right way of doing that is:

shared_ptr source(new int);
*source = 3;
shared_ptr
destination = source.get();
destination = source;

In this way, the pointer counters are updated and no problems occur while running the program, since the operator = is properly overrided in the class.

No comments:

Post a Comment