Boost weak_ptr's in a multi-threaded program to implement a resource pool

前端 未结 3 1700
时光说笑
时光说笑 2020-12-11 07:32

I\'m thinking of using boost::weak_ptr to implement a pool of objects such that they will get reaped when nobody is using one of the objects. My concern, though, is that it

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-11 08:01

    Both boost::weak_ptr and boost::shared_ptr are similar if it comes to thread safety: they are not thread safe if there is a risk that object is going to be destroyed somewhere. If your object referenced in boost::shared_ptr or weak_ptr is being referenced permanently somewhere, then use can use shared/weak ptrs without any risk.

    But if some operation is going to dereference the last living instance of object, then at that time you cannot do some operations on weak_ptr: in particular: you cannot assign weak_ptr to another weak_ptr because it uses shared_ptr internally. Also, you cannot use lock because the result is undefined. Also, expired() method is useless to: it may return true, but then next line of your code, your object might be already expired.

提交回复
热议问题