Outline
weak_ptr not control is a smart pointer object lifetime points, it points to an object managed by a shared_ptr. A weak_ptr bound to a shared_ptr shared_ptr does not change the reference count. And once the last shared_ptr is destroyed, it points to the object will be released, even if at this time there are still weak_ptr points to the object will be released.
Since the object may not exist, we can not use weak_ptr direct access to the object, but you must call the lock. This function checks whether weak_ptr pointed object still exists. E.g:
if (shared_ptr<int> np = np.lock()) { // 如果np不为空则条件成立
cout << *np << endl; // 此时可以访问其对象
}
Common Operations | Usage Notes |
---|---|
weak_ptr< T > w | Empty week_ptr can point to an object of type T, |
weak_ptr< T > w(sp) | And the same object point shared_ptr sp weak_ptr. T must be converted to the type of pointing sp |
w = p | p can be one or a shared_ptr weak_ptr. After the assignment p w and shared objects |
w.reset() | The blank w |
w.use_count() | The number of shared objects w shared_ptr |
w.expired() | If w.use_count () is 0 returns true, false otherwise |
w.lock() | If w.expired () is true, returns an empty shared_ptr, otherwise its binding shared_ptr |