[SOLVED] Reuse a QDirIterator
-
I would like to assign a new directory to a QDirIterator that I have allocated in my constructor with an empty directory. I want to do that to avoid having to deal with memory management. I only need one Iterator at a time and would like to repurpose one variable.
-
QDirIterator does not expose such api, but I wouldn't worry that much about it. It's a fairly lightweight class. I wouldn't make an instance of it part of your class. Just allocate it on the stack whenever you need it.
-
Like @Chris-Kawa said: Create it when you need it. But if you really always want to have a copy around and you're worried about memory management then use a smart pointer:
std::unique_ptr<QDirIterator> m_it; // member variable // ... , m_it( new QDirIterator("") ) // initialize in constructor // ... m_it.reset( new QDirIterator("/home", QDirIterator::Subdirectories) ); while (m_it->hasNext()) { qDebug() << m_it->next(); }
-
@Wieland That's still recreating the iterator every time, just placed in an extra wrapper. It's basically like
std::unique_ptr<QString>
. There's no point to do it whatsoever. -
@Wieland That's still recreating the iterator every time, just placed in an extra wrapper. It's basically like
std::unique_ptr<QString>
. There's no point to do it whatsoever.@Chris-Kawa The point is that he can reuse the iterator in case he doesn't need to change the path always. But I wouldn't do it.
-
This wouldn't reuse the iterator. It is recreated by this
m_it.reset( new QDirIterator("/home", QDirIterator::Subdirectories) );
. The pointer is the same, but the iterator is a whole new instance. If the path doesn't change it's still better to store it (e.g. in QString) and use a stack based instance with it than to store that pointer and recreate the iterator anyways. -
This wouldn't reuse the iterator. It is recreated by this
m_it.reset( new QDirIterator("/home", QDirIterator::Subdirectories) );
. The pointer is the same, but the iterator is a whole new instance. If the path doesn't change it's still better to store it (e.g. in QString) and use a stack based instance with it than to store that pointer and recreate the iterator anyways.@Chris-Kawa Yes, of course.