How to comprare weak_ptr with shared_ptr | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to comprare weak_ptr with shared_ptr

Hi I have tried to use smart pointer for implementation of Circular Singly Linked List as below: https://code.sololearn.com/cgIlijAT32A0 I observed that destructor for node class is not called for any of the node used in linked list. Reason is but obvious and it is circular reference due to shared_ptr used in node class. I just tried to change next member variable of node class (shared_ptr<node> next;) to weak_ptr and it fails to compile. I have two questions now as below: 1. Can I compare weak_ptr with shared_ptr any how to make line 30 [while(tmp->next != head) in void circularList::createList() method] get compiled? 2. If not, how can I create object of weak_ptr from fresh as it has to be compared with head pointer of type shared_ptr Feel free to ask for clarification. Thanks in advance..!

16th Aug 2021, 2:05 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 1
I tried using the lock() function but that didn't work 😔. It called the destructor though. Did you find a solution? And why is it important to make it a weak pointer? https://code.sololearn.com/cRrQQsMzEkbr
24th Aug 2021, 5:54 AM
Edward Finkelstein
Edward Finkelstein - avatar
0
No not yet.... Thanks for your help and effort. Regarding weak pointer, it doesn't add count in reference mechanism. For example, there are two nodes having value 1 and 2. In case of shared_ptr as node class member, we will store reference of node 1 into node 2 and node 2 reference in node 1. This way both have reference as 2 and none of them goes deleted as it is referring to each other. And hence, memory will not be released for them. If it would have been weak_ptr , it is not the case. Hope it is clear. If not, feel free to let me know and will try to explain.
24th Aug 2021, 6:12 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
I get that much, but I don’t get why one can’t do the same operations on weak pointers as with shared pointers, like assignment and ==.
24th Aug 2021, 8:25 AM
Edward Finkelstein
Edward Finkelstein - avatar
0
Because they are object of two different template classes. Implicit conversion not provided as one just refer the memory address and does not hold where as other occupies that location for own's life scope
24th Aug 2021, 9:11 AM
Ketan Lalcheta
Ketan Lalcheta - avatar