Question: Recall how weak pointers work. Weak pointers are an extension of shared (strong) pointers such that a weak pointer to an object won't be considered

 Recall how weak pointers work. Weak pointers are an extension of
shared (strong) pointers such that a weak pointer to an object won't
be considered in the reference count, and objects can be deleted even

Recall how weak pointers work. Weak pointers are an extension of shared (strong) pointers such that a weak pointer to an object won't be considered in the reference count, and objects can be deleted even if there are weak references to them. Consider this partial implementation of weak pointers. It has the following properties: - each smart pointer (shared or weak pointer) points to a control block which contains: strong_count: the number of shared_ptr references to the object weak_count: the number of weak_ptr references, plus one if strong_count >0 ptr: the pointer to the object - objects are destroyed when the strong_count reaches 0 - control blocks are destroyed when the weak_count reaches 0 - weak pointers cannot be directly used; the user must first promote it to extract a strong pointer that can then be dereferenced if the object has been destroyed, promote fails and returns nullptr we cannot dereference weak pointers directly because the object could have been destroyed (expired) Don't overthink implementations! They will be at most a few lines each. -shared_ptr() i I/ your implementation here 3 II other operators similar to p4, but update strong_count 3; friend class weak_ptreT>; // allow weak_ptr to have access to shared_ptrificb templatectypenane T> class weak ptr \{ control_block T>cb public: II weak pointers are constructed from shared pointers, II since a weak pointer with no strong references is automatically expired weak_ptr(const shared_ptr & cb->weak_count, add_fetch (1); 3 weak_ptr(const weak_ptr\& rhs) : cb( rhs,cb) \{ cb->eak_count,add_fetch(1); 3 weak_ptro f II your implementation here 3 bool is expired() const \{ Il your implementation here 3 shared_ptreT> promote() \{ II your implementation here 3 I/ copy/move constructors and operators are the same as p4, but update weak_count Finish the promote method. You can create a null shared pointer by shared_ptreT> ptr\{f: and since weak_ptr is a friend class of shared_ptr, you have access to the control block of a shared pointer

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!