Is it a bad idea to define a static array member variable for an iterator?
In the following nested loop, will the static array be created and destroyed for 1000 times? (suppose we use compiler optimization)
X
is a range object with begin()
and end()
member functions. The two member functions both return an iterator with a static array member variable.
for (int i = 0; i < 1000; ++i) {
for (auto i: X) {
// do stuff.
}
}
I assume you want to copy something into the static array on iterator construction on each loop. I further assume that you overwrite the entire array and you're doing this because you've realized that data would get lost otherwise. I'd be happy to throw away that assumption if you use it for sg. else, but that's a very common issue with range for. Your code won't be reentrant, let alone thread-safe. That means that, depending on how you do this, you might not even be able to do nested loops. That's a very bad idea... ... yuck, just about as bad as you get with range for vs. temporaries. Perhaps the best thing/workaround to do is keeping a shared_ptr<> to what you want to keep. This might include the range itself if you write this owning begin() and end() for the ptr, not the range. (Either this obscurity or potential UB from enable_shared_from_this()).
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments