Re: Do vector iterators remain valid after resize() if base pointer
of elements remains unchanged?
zr wrote:
On Mar 24, 12:56 pm, zr <zvir...@gmail.com> wrote:
I hope the following example illustrates the question:
#include <vector>
int _tmain(int argc, _TCHAR* argv[])
{
std::vector<int> sorted_image_id;
//..
sorted_image_id::pointer base = &sorted_image_id.front();
sorted_image_id.resize(sorted_image_id().size()*4);
if (&sorted_image_id.front() == base)
{
//Is it safe to assume all iterators are still valid?
} else
{
//Need to reassign iterators
}
//...
return 0;
}
Here is a corrected version that passes compilation:
"Passes compilation"? Not on my compiler. '_TCHAR' is undefined.
int _tmain(int argc, _TCHAR* argv[])
{
float resize_factor = 1.3;
std::vector<int> sorted_image_id;
//..
int* base = &sorted_image_id.front();
sorted_image_id.resize(sorted_image_id.size()*resize_factor);
// optimization: reuse iterators after resize
if (&sorted_image_id.front() == base)
{
//Is it safe to assume all iterators are still valid?
} else
{
//Need to reassign iterators
}
//...
return 0;
}
'std::vector' is very sensitive WRT its iterators. If reallocation
occurs, all iterators are invalidated. So, if your pointer comparison
is designed to see whether the reallocation has occurred (which it would
seem to do), then you're probably OK. I don't know much about the
systems on which loading an invalid pointer into a register can trip the
hardware signal, so I can't vouch for the cases when 'base' is compared
with the address of the first element after becoming invalid on such
systems. FAIK, it could be a trap. The only value guaranteed to work
(when compared with any other pointer) is a null pointer value.
Of course, hardware interrupt upon loading of a pointer value that just
became "invalid" is highly unlikely, so you're *most likely* fine.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask