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

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

20th Apr 2020, 10:22 AM
你知道規則,我也是
你知道規則,我也是 - avatar
2 Answers
+ 1
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-
20th Apr 2020, 10:45 AM
Stephan
Stephan - avatar
+ 1
I think you don't use weak_ptr because shared is enough. https://code.sololearn.com/cSykNJpe6fsZ/?ref=app
21st Apr 2020, 3:11 AM
RainStorm
RainStorm - avatar