1

Consider the following:

std::unordered_map<int, std::array<float,50>> foo;
...
auto pointerToArray = foo.at(3).data();

I have read this and this. I have the following questions:

  • 1) pointerToArray falls into which category when referring to the invalidation rules, iterator or reference?
  • 2) What are the risks that pointerToArray will get invalidated (assuming its paired key in foo is not erased)?
  • 3) What, if any, difference is there in the answers to these questions between unordered_map and map ?

Unlike vector, array itself will not re-allocate and thus there is not a risk of it changing memory addresses on its own, but as it is inside a unordered/map, the plot thickens.

Update: Found another question that suggests there is no risk of invalidation in this case.

7
  • 1
    It's pretty clear to me that this goes the same as invalidating a pointer to a struct. Commented Jul 11, 2016 at 18:55
  • You should not think in terms of risk. Either it works or it doesn't. Commented Jul 11, 2016 at 18:56
  • 1
    I don't understand how your second link does not answer your question. A pointer to something is basically the same as a reference to something. Commented Jul 11, 2016 at 19:00
  • 1
    @NathanOliver I suppose part of the confusion is the standard's use of the word "reference" when I'm not using any C++ references in my example, hence my first question. Edit: I see you just changed your comment to answer the question in this reply. Commented Jul 11, 2016 at 19:01
  • @johnbakers Typically a reference is implemented as a pointer. So you can interchange them in this context. Commented Jul 11, 2016 at 19:02

1 Answer 1

1

Based on the information provided by the first link you provided, pointerToArray should NOT be invalidated by any subsequent changes made to the map, unless you were to erase the element itself from the map. The std::array<float, 50> object will be stored in the heap, and only the pointer (or possibly reference, depending on how std::unordered_map is implemented) to that object will be shuffled around within the map.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.