-2

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;
};
TSG
  • 4,242
  • 9
  • 61
  • 121
  • 3
    Where is `foreach` coming from? That's not standard C++. – ShadowRanger Feb 25 '22 at 22:24
  • As I mentioned in a comment to [this question of yours](https://stackoverflow.com/questions/71271359/how-to-pass-an-object-address-created-at-time-of-function-call), please try to make a [mre]. – Ted Lyngmo Feb 25 '22 at 22:30
  • Whichever language it turns out to be (the syntax doesn't match `foreach` in C# or `forEach` in Java), the answer is *probably* going to be that you should make `commandName` a *reference* variable. How to do that depends completely on the language. – Adrian Mole Feb 25 '22 at 22:34
  • 2
    my guess ' foreach' is a macro that does roughly what a ranged for does.(from before ranged for). But we need to see it – pm100 Feb 25 '22 at 22:40
  • @pm100 Good guess: https://stackoverflow.com/q/10522155/10871073 – Adrian Mole Feb 25 '22 at 22:41

1 Answers1

1

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);

?

chehrlic
  • 913
  • 1
  • 5
  • 5
  • This is new to me....m_registeredResponseObjects is a QMap so will this for loop fill val with the pointer of each map entry? (How does it know not to return the key)? I couldn't find a good explanation of qAsConst used like this – TSG Feb 26 '22 at 12:53
  • 1
    Simply try it out - Qt containers do return the value in a range-based for loop. And even if you don't trust it, use Q_FOREACH as in your example... For qAsConst -> see the [documentation](https://doc.qt.io/qt-5/qtglobal.html#qAsConst) – chehrlic Feb 26 '22 at 16:26