2013 m. birželio 19 d., trečiadienis

The dangers of C++ smart pointers

I've spent an entire day debugging a single segfault in Gnote! Luckyly it only occurred "sometimes" when closing application. It was an issue with C++ smart pointer, Glib::RefPtr to be exact. Here are some dangers you might encauter with all types of smart pointers:
  • Mixing smart and simple pointers is never a good idea, SPs only trully work when used entirely everywhere
  • Make sure you know how pointer WORKS, look at it's source code, if required. Assumptions is evel everywhere, but here they can bring the house down (as could have happened in Gnote)

On issue in Gnote
Glib::RefPtr is designed to point to descendants of Glib::Object, but is not limited to them. It requires that object has methods reference() and unreference(), which do reference counting and, if necessairy, delete the object. The problem is, that RefPtr constructor expects object to have a counter of 1 and does not call reference() (probably related to how GTK+ works). However the destructor does call unreference(). So, if you create RefPtr passing an object, that's already referenced by other RefPtr's, objects internal counter is less than actual number of RefPtr pointing to it. As a result when all RefPtr's are destroyed, you might get crash on some later of them with some nice time to chase this bug down :)

Komentarų nėra:

Rašyti komentarą