0

In the linked code, I am trying to pass an std::map to the thread as a reference (using std::ref). However, sometimes when the map is accessed my the thread it is empty.

darkspine
  • 651
  • 1
  • 6
  • 17
  • 1
    Please include a [mcve] in the question – 463035818_is_not_an_ai May 10 '20 at 08:41
  • 1
    You may have a race on `options` vector. You give the worker thread a reference to the vector's element, then add to the vector - this may cause the vector to reallocate its storage, which invalidates all pointers, references and iterators into it. – Igor Tandetnik May 10 '20 at 11:15
  • @IgorTandetnik, I did not expect the vector a stored element. Is there any other size flexible stl containers which wont do this? Do i need to pass pointers? – darkspine May 10 '20 at 11:33
  • 1
    `std::deque` doesn't invalidate pointers or references when elements are added at either end. Or, you could just pass the map to the thread by value, so it gets its own copy. – Igor Tandetnik May 10 '20 at 12:04

1 Answers1

0

std::vector invalidates pointers or references when elements are added.

I ended up using a std::vector of std::unique_pointers to store the map.

Use a std::deque or pass by value.

As commented by Igor Tandetnik.

Also refer this answer

darkspine
  • 651
  • 1
  • 6
  • 17