jeudi 25 octobre 2018

std::unordered_set iterators don't appear to be invalidated by rehash

I was reviewing some old code of mine and I realized that the code was incorrect since it was using std::unordered_set iterators across rehashes. To convince myself, I wrote a small C++11 program which tries to re-use iterators after a rehash:

#include <unordered_set>
#include <vector>
#include <iostream>

int main() {
  std::unordered_set<int> s(5);
  std::vector<std::unordered_set<int>::iterator> its;
  for (int i = 0; i < 100; i++) {
    auto it = s.insert(i);
    its.push_back(it.first);
  }
  s.rehash(200);  // force rehash just in case...
  for (auto it : its) {
    std::cout << *it << "\n";
  }
  for (auto it2 = its[0]; it2 != s.end(); it2++) {
    std::cout << *it2 << "\n";
  }
  for (auto it : its) {
    s.erase(it);
  }
  std::cout << s.size() << "\n";
  return 0;
}

I compiled this program and was able to run it fine under Valgrind, which is not really what I was expecting. I tried with both g++ (5.4.0) and clang++ (3.8.0) and didn't get any memory error in either case. Could someone explain why? Is it specific to the g++ & clang++ STL implementations which provide additional "guarantees"? Or is there an issue with my test program.

Aucun commentaire:

Enregistrer un commentaire