Search code examples
c++qtpointersshared-ptrqsharedpointer

How to prevent deletion of pointers managed by a QSharedPointer


I have some intermittent segmentation faults in a Qt application. I think the problem is related to our (bad) use of QSharedPointer. The Qt Documentation states :

QSharedPointer::QSharedPointer ( T * ptr ) : Creates a QSharedPointer that points to ptr. The pointer ptr becomes managed by this QSharedPointer and must not be passed to another QSharedPointer object or deleted outside this object.

I think we are doing both must not... :/

Is there a OOP way to enforce that the pointer managed by QSharedPointer cannot be deleted or passed to another QSharedPointer?

The best solution will be to have a compiler error.


Solution

  • The normal pattern is to put the new statement inside the smart pointer's constructor, like this:

    QSharedPointer<Obj> p (new Obj(2)); 
    

    That way you never have a reference to the naked pointer itself.

    If you refactor your code so that all new operator are in lines like these, all your problems will be solved.