Supporter Mike
Supporter Mike

Reputation: 23

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

Upvotes: 2

Views: 79

Answers (2)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122321

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

Upvotes: 2

molbdnilo
molbdnilo

Reputation: 66371

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.

Upvotes: 1

Related Questions