Home > Software engineering >  Why are STL's iterators exposing their container's internals? Why are iterator's memb
Why are STL's iterators exposing their container's internals? Why are iterator's memb

Time:06-10

std::list's iterator is a struct, not a class.

In some implementations, it has the node pointer public and accessible to the user. Therefore, a user should be able to "accidentally" modify a link and break the relationships within the list through an iterator. Why is this possible?

I do get that the member functions of containers (the ones that modify the container) frequently need to extract the underlying pointers from the iterators, but can't the container itself be a friend to the iterator? And the internals of it [the iterator] be declared private?

Doesn't this violate encapsulation and OOP principles?

Can you explain the logic behind this decision? Why doesn't the standard require the iterators' internals to be private?

CodePudding user response:

Why are STL's iterators exposing their container's internals?

They don't.

Why doesn't the standard require the iterators' internals to be private?

Because that would be of no gain. The standard does not specify that the members are publicly accessible and that should be enough to know that you shall not write code that assumes the members are publicly accessible.

If you are working with an implementation where those members are public and you do access them then you are relying on implementation details and your code is not portable.

  • Related