dimanche 2 avril 2023

Using std::vector iterator after calling clear()

This issue is very strange, I have following code:

#include <iostream>
#include <thread>
#include <chrono>
#include <string>
#include <vector>

struct Data {
    Data(const char * d)
        :data(d){}
    std::string data;
};

// Using these data to avoid SOO(aka small object optimize) ASAP
std::vector<Data> arr {"11111111111111111111111111111111111111111111111111111111",
                        "2222222222222222222222222222222222222222222222222222222",
                        "3333333333333333333333333333333333333333333333333333333",
                        "4444444444444444444444444444444444444444444444444444444",
                        "5555555555555555555555555555555555555555555555555555555"};

class Test {
public:
  void test() {
    // I get a valid iterator first
    std::vector<Data>::iterator it = arr.begin();

    // I run a thread to clear arr
    std::thread([](){
          std::this_thread::sleep_for(std::chrono::seconds(2));
          arr.clear();
        }).detach();
    // sleep 3s to make following code run after thread
    std::this_thread::sleep_for(std::chrono::seconds(3));
    // I think it->data is a invalid operation, Howerver, it works :(
    std::string res = it->data;
  }
};

int main() {
  Test test;
  test.test();
  std::this_thread::sleep_for(std::chrono::seconds(5));
  return 0;
}

This case shows visiting a iterator after calling clear(), theoretically it is a invalid operation, but it works, I very wonder it, why why why???

Aucun commentaire:

Enregistrer un commentaire