[SOLVED] Reuse a QDirIterator
-
wrote on 11 Apr 2015, 07:27 last edited by Hazzl 4 Nov 2015, 19:07
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.
-
wrote on 11 Apr 2015, 11:23 last edited by
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.wrote on 11 Apr 2015, 11:30 last edited by A Former User 4 Nov 2015, 11:31@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.wrote on 11 Apr 2015, 11:38 last edited by@Chris-Kawa Yes, of course.
-
wrote on 11 Apr 2015, 19:05 last edited by
Thanks a lot for your pointers (no pun intended :-)
1/8