Search code examples
c++stdvector

std::vector, member access operator and EXC_BAD_ACCESS


Why can I execute an operator& from a (*iterator), but can not make copy of value (*iterator) ?

std::vector<int> v;   // yes, container is empty
for (int i = 0; i < 10; ++i) {
    auto it = v.begin();
    std::cout << &*(it) << std::endl;   // 0   <- why not EXC_BAD_ACCESS?
    auto value = *(it);                 // EXC_BAD_ACCESS
    auto address = &value;
}

Solution

  • v is empty, hence v.begin() == v.end() and dereferencing it is undefined.