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

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. - sharedptro Il your inplementation here Il other operators 51mi lar to p4, but update strong_count 3. Friend class weok_ptrots; // allow weak_ptr to have access to shared_ptri: icb templatestypenane Ts class weak ptr \{ control_block T T cb; public: 1/ weak pointers are constructed from shared pointers, If since a weok pointer with no strong references is automatically expired weak ptr(const shared ptret>\& rhs) : cb(rhs.cb ) i \} weak_ptr(const weak_ptr\& ris) : cb(rhs,cb) \{ cb->weak_count. add_fetch (1); \} -weak_ptro \& /I your implementation here 3 bool is_expiredO const f I/ your implementation here 3 shared_ptreTs promote() f II your implementation here 3 1/ copy/move constructors and operators are the sane as p4, but update weak_count 3 Question 2 Consider the reasons for this design. a) Why is a control block needed, instead of using internal reference counts as we did in p4? b) We can delete control blocks when no shared_ptr or weak_ptr references it. Why do we add one to the weak_count if the strong count is nonzero, instead of just checking both the weak and the strong count before deleting? (Hint: consider multithreading

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!