tags:

views:

172

answers:

3

Suppose I have this code...

class GraphFactory : public QObject
{
private:
    QMap<QString, IGraphCreator*> factory_;

public:
    virtual ~GraphFactory();
};

GraphFactory::~GraphFactory()
{
    // Free up the graph creators
    QMap<QString, IGraphCreator*>::iterator itr;
    for (itr = factory_.begin(); itr != factory_.end(); itr++)
    {
     IGraphCreator * creator = itr.value();
     delete creator;
     creator = NULL;
    }

}

When is the QMap factory_ destroyed? Before the call to the destructor, or during the destructor? (I understand that the destructor will be called when an instance of GraphFactory goes out of scope. But when are the non-pointers member destroyed?)

Edit: I am getting invalid values for the factory_ map when it reaches the destructor. A break point shows that the value wouldn't have tampered with the value stored inside the QMap.

+7  A: 

It'll be destructed after the destructor code gets executed

The idea is to have access to your members in the destructor code so they get destroyed after it gets executed.

Arkaitz Jimenez
+2  A: 

After GraphFactory::~GraphFactory, but before QObject::~QObject. So actually between destructors.

MSalters
+1  A: 

If the data stored in GraphFactory::factory_ member is invalid when your destructor is being called there are a number of ways this could happen e.g. A double free of your GraphFactory instance, or perhaps something is overwriting it in error.

If you happen to be running on Windows then tools like Application Verifier can be very helpful when debugging this type of problem (use it to enable Page Heap feature and attach a debugger when reproducing the problem).

If are using your GraphFactory class in a multi-threaded environment you should synchronise access to the QMap instance because "bad things" can happen if you don't.

I'm not aware of equivalent tools for other platforms. I'd love to hear about them if anyone reading this happens to know.

Paul Arnold