2

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;
}
5
  • For me after giving v some elements it all worked (in g++,clang,msvc) Commented Oct 18, 2022 at 8:55
  • You should not assume that bad code (in your case *(it)) always produces an error. Instead all it means is that the behaviour of your code is undefined. For such code questions like 'why' and 'why not' are meaningless. Commented Oct 18, 2022 at 8:55
  • 1
    @BotondHorváth I think the point is that v has no elements. Commented Oct 18, 2022 at 8:56
  • Undefined behaviour is undefined. Commented Oct 18, 2022 at 8:59
  • @john i assumed that in the real case it wasn't, he just forgot to put initialivation in the example. If v fas no elements *it kindof means v[0] which is UB (index out of range) Commented Oct 18, 2022 at 9:26

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Could you please refer to documentation or other source to understand why *(v.end()) is Undefined behaviour?
@SupporterMike cppreference: "This element acts as a placeholder; attempting to access it results in undefined behavior. "
1

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.

1 Comment

An accessible explanation why dereferencing such an iterator does not yet throw an exception. Together with the answer from @463035818-is-not-a-number fully answers the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.