Object delete itself from container

后端 未结 4 1005
耶瑟儿~
耶瑟儿~ 2021-01-16 15:59

So I have a container(any kind, probably std::map or std::vector) which contains objects of a class with some network thing running in a thread that checks if it is still co

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-16 16:24

    In order for the object to delete itself from the container, it will have to know which container it is in. You will need to maintain a pointer to the container in the object. You will also have to protect the container with a lock to stop multiple threads accessing the container at the same time.

    I think I prefer your second solution - some managing object looks after removing dead objects from the collection. If nothing else, this will be quite a bit easier to debug and the locking logic becomes centralised in a single object.

提交回复
热议问题