1

Is it necessary to clear all the inner lists to avoid a leak?:

class Instruction
{
    int opcode;
    int data1;
    int data2;

    bool Load(QTextStream* in);
    void Save(QTextStream* out) const;
};

class Interpreter
{
    QList<QList<Instruction>> steps;

    bool Load(QTextStream* file)
    {
        if(file_is_bad)
        {
            return false;
        }

        int end = steps.size();
        for(int i=0; i<end; i++)
        {
            steps.at(i).clear();
        }
        steps.clear();

        //now that it's clear, rebuild it from file
        return true;
    }
};

Or can I just call steps.clear(); and call it a day?


(And here's some more text to get past the "too much code" error.)

AaronD
  • 503
  • 1
  • 7
  • 23
  • 2
    `steps.clear()` alone is sufficient. It runs destructors on all its elements, and `QList` destructor is essentially the same as `clear()` – Igor Tandetnik Dec 23 '15 at 23:23
  • 1
    though if inner list contains pointers created with new, qDeleteAll() should be called for each nested list as well – Shf Dec 23 '15 at 23:24
  • If `Instruction` doesn't produce memory leaks, `QList>` on stack won't as well. You can run valgrind to check for memory leaks. – Simon Warta Dec 24 '15 at 18:18
  • @SimonWarta: Does it make a difference if Interpreter is in the heap (via new), seeing that the QList> is a member object? – AaronD Dec 24 '15 at 22:23
  • @AaronD I was not really precise with my wording (see also http://stackoverflow.com/a/11477572). Since it is a member, `QList> steps;` is properly destroyed as soon as your `Interpreter` instance is destroyed, from heap or from stack. So "just call steps.clear(); and call it a day". – Simon Warta Dec 24 '15 at 22:34
  • @SimonWarta: Okay. If you'd like to make an answer to that effect, I'll accept it. Thanks! – AaronD Dec 24 '15 at 22:45

1 Answers1

1

Igor was right. steps.clear() is enough because it destroys all inner QLists. Destroying an inner QList calls the destructor of all Instruction instants.

So as long as a single Instruction does not leak memory (e.g. by calling a new in the constructor but no delete in the destructor), QList<QList<Instruction>> will not leak as well.

Simon Warta
  • 10,850
  • 5
  • 40
  • 78