简体   繁体   English

具有弱指向容器元素的指针的C ++迭代器

[英]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. 因此,无论是否为weak_ptr

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. 这是容易出错的方式,并且会导致问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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