简体   繁体   中英

C++ iterator with weak pointers to container elements

I have a generic tree container and I would like to implement an iterator to traverse his elements. In the main container I used shared pointers to connect the various nodes of the tree.

Does it make sense to implement an iterator using weak pointers?

The point is: if I remove a node from the tree while I am using the iterator, the node resources will be deallocated only when the iterator is destructed (if I use shared pointers). With weak pointers, I presume that the resources are deallocated at once (maybe making the iterator inconsistent, but this is not important).

Can you think of other solutions to this problem?

First, iterators contains only a pointer to container element, not element itself. So no matter it was weak_ptr or not.

So if you remove element from a container, iterator can become invalid . This means it can point to trash memory, freed memory, not-your-memory, another element (not which you think) and so on.

This is error-prone way and will lead to problems.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM