logoalt Hacker News

rerdavies • today at 4:28 AM • 2 replies • view on HN

It's probably nice to know WHY you might need weak_ptr.


Replies

cowlevel • today at 6:34 AM

Explanation: shared_ptr is an implementation of "reference counting". All shared_ptrs to the same object collaborate to know how many of them exist (it's just a ++ on creation of one, -- on destruction of one) and when the last one is destroyed it also destroys the object that's pointed to.

weak_ptr is like shared_ptr but doesn't add to the count. When the last shared_ptr is destroyed it destroys the object even if there are still weak_ptrs. Any weak_ptrs pointing to that object become null. I won't dive into how that's actually implemented. Obviously it costs some CPU cycles to make that happen, so you don't see shared_ptr or weak_ptr a lot in code that's written with a performance mindset. Although you're still getting 90% of the performance benefit by writing C++ instead of JS even if it's "inefficient" C++.

I agree with GP's point and add, if this isn't something you need to do, then don't even think about it. C++ is like a toolbox with a bunch of tools. I don't study all the tools before building a table, I look up how to build a table, and then see if the tools are in my toolbox. Studying the triangle screwdriver would be a waste of time and only confuse me more, unless I'm trying to drive triangle screws. Only when I need to drive a triangle screw then I can look for the triangle screwdriver.

pjmlp • today at 7:22 AM

For the same reason you need weakref in Python, to handle circular references in memory managed via reference counting GC algorithm.

https://docs.python.org/3/library/weakref.html

Anyone that thinks Python is "simple", to come back to some of the suggestions on how it is easier than C++, they really should learn the language reference, standard library, and CPython FFI manuals.

➕ show 1 reply