2

As pointed out in answer to another question, all pointers to a vector's elements may become invalid after new elements have been added to that vector, due to reallocation of the underlying contiguous buffer.

Is there a safe way to handle this issue at compile-time?

Are there best-practices to deal with or to avoid a situation, where references may become invalid after altering the data-structure?

Community
  • 1
  • 1
wotanii
  • 2,470
  • 20
  • 38
  • in c# I will get an exception when I add elements while a iterator is active. Can I recreated this behavior in c++? – wotanii Jan 10 '17 at 06:21
  • Can I tell the compiler to throw an error whenever I store a reference to a element in a vector? If so I might work around the issue by always getting the element by its index. – wotanii Jan 10 '17 at 06:24

2 Answers2

1

Are there best-practices to deal with or to avoid a situation, where references may become invalid after altering the data-structure?

  • preallocate enough space for vector in advance
  • keep index of object in array instead of reference/pointer to object itself
  • use different container, for example std::list

which way will work for you the best way depends on your situation

Slava
  • 43,454
  • 1
  • 47
  • 90
-1

A pointer or reference to the std::vector itself won't change. What could change is the address of a specific element inside the std::vector due to reallocation policy which is implementation dependent.

Preallocating enough space is a risk because you shouldn't relay on a particular implementation policy.

Storing the address of an element in a std::vector is a bad idea and can be easily avoided because std::vector [] operator is very fast so store the index instead the address of the element. This the right way.

Javier
  • 1
  • 1