当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - What should I do when someone dereferences my end() iterator?

问题描述:

I am writing a custom container class, with a custom iterator.

I am avoiding STL because I am an embedded C person and don't understand the STL well enough to trust myself to write a custom container and iterator with it.

If someone tries to deference my iterator (using (*it).Whatever() ) when it is one-past-the-end, I get a segfault. That's expected because internally it's a NULL pointer.

Currently my * override looks like this:

Event& EventList::iterator::operator*()

{

return * m_pBlock->GetAt(m_EventIdx);

}

So, what should I do?

  1. Throw an exception? Which one? I am trying to avoid exceptions though.

  2. Give up on emulating STL and return a pointer or NULL pointer from my iterator.

  3. Keep a global static Event instance around to use as an error return value.

  4. Something else.

I have to say that I am very suspicious of the practice of returning references, since there is no way to return a NULL reference. The whole idea doesn't seem very well thought out.

Maybe someone could explain what it is that I am missing about the concept of returning references.

Thank you.

网友答案:

Generally speaking, the STL specifies its own iterators as causing UB when you dereference end(). You can do the same. So you don't need to do anything here to be compatible with the STL in every way. There may be other aspects that are wrong, but this behavior is perfectly valid.

分享给朋友:
您可能感兴趣的文章:
随机阅读: