About shared_ptr and weak_ptr | Sololearn: Learn to code for FREE!


About shared_ptr and weak_ptr

I code a simple container with shared_ptr. I want to print the elements it has. I found both shared_ptr and weak_ptr can do the job and won't cause memory leak (I think?). Which is prefered? Or is there a way better than any other? https://code.sololearn.com/c63mwyD128VG

4/20/2020 10:22:47 AM


2 Answers

New Answer


Hi. In this case you don't need weak_ptr, shared_ptr is well enough. You should use weak_ptr if you have 2 shared_ptr that point to each other. There is a good example https://riptutorial.com/cplusplus/example/1673/sharing-with-temporary-ownership--std--weak-ptr-


I think you don't use weak_ptr because shared is enough. https://code.sololearn.com/cSykNJpe6fsZ/?ref=app