Home > Net >  std::vector, member access operator and EXC_BAD_ACCESS
std::vector, member access operator and EXC_BAD_ACCESS

Time:10-18

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;
}

CodePudding user response:

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

CodePudding user response:

In theory, both have undefined behaviour and anything can happen in either case.

In practice, &*(it) does not access any memory; you don't need to read from a location in memory in order to determine what that location is.
(Somewhat similarly, you can figure out the address of a house without entering it, and the house doesn't even have to exist.)

Copying something, on the other hand, does require you to read what that thing is.

  • Related