Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointers into elements in a container

Tags:

c++

pointers

stl

Say I have an object:

struct Foo 
{
    int bar_;
    Foo(int bar) bar_(bar) {}
};

and I have an STL container that contains Foos, perhaps a vector, and I take

// Elsewhere...

vector<Foo> vec;

vec.push_back(Foo(4));

int *p = &(vec[0].bar_)

This is a terrible idea, right?

The reason is that vector is going to be storing its elements in a dynamically allocated array somewhere, and eventually, if you add enough elements, it will have to allocate another array, copy over all the elements of the original array, and delete the old array. After that happens, p points to garbage. This is why many operations on a vector will invalidate iterators.

It seems like it would be reasonable to assume that an operation that would invalidate iterators from a container will also invalidate pointers to data members of container elements, and that if an operation doesn't invalidate iterators, those pointers will still be safe. However, many reasonable assumptions are false. Is this one of them?

like image 397
Pillsy Avatar asked Dec 13 '22 22:12

Pillsy


1 Answers

The standard specifies when such pointers are invalidated. References into a vector die when you increase its size past capacity or add/remove a preceding element. References into a deque are invalidated if you add/remove from the middle.

Otherwise, references and iterators are safe to keep for the lifespan of the underlying object.

like image 194
Potatoswatter Avatar answered Dec 15 '22 13:12

Potatoswatter