Home > front end >  Why is this allocating an unneeded temporary container
Why is this allocating an unneeded temporary container

Time:02-27

I am getting a warning against my foreach loop that I'm "allocating an unneeded temporary container" but I have no idea what that means.

foreach(QString commandName, m_registeredResponseObjects.keys()) {
    delete m_registeredResponseObjects[commandName];
};

Does this means the key() method is called on each iteration of the loop? I don't even see the container the warning is referencing...

foreach is a Qt macro defined as

template <typename T>
class QForeachContainer {
public:
    inline QForeachContainer(const T& t) : c(t), brk(0), i(c.begin()), e(c.end()) { }
    const T c;
    int brk;
    typename T::const_iterator i, e;
};

CodePudding user response:

It means that you create a container with this statement: m_registeredResponseObjects.keys() for no good reason. This function iterates over your m_registeredResponseObjects, collects all keys and returns a container where you then iterator over just the get the values from m_registeredResponseObjects by key. This makes no sense at all - why not simply

  for (auto val : qAsConst(m_registeredResponseObjects))
    delete val;

or even simpler with the Qt macro qDeleteAll()

  qDeleteAll(m_registeredResponseObjects);

?

  • Related