2

I was in an interview explaining smart pointers and when I was saying about weak pointer that they actually behave like shared pointers but they don't increment the number of pointers pointing at a resource. So when all shared pointers get out of scope and the counter reaches zero the resource gets de allocated even if there is a weak pointer pointing at it. Then he asked me why we might need a weak pointer. I didn't know the answer and he told me we use them when we want to take the ownership of a resource, but I didn't really understand what that means. Can someone explain that to me?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
  • Here is already an answer to the same/similar question: https://stackoverflow.com/questions/12030650/when-is-stdweak-ptr-useful – Rushikesh Jun 07 '19 at 12:51
  • If something is missing from the dupe, poke me – Guillaume Racicot Jun 07 '19 at 12:52
  • The duplicate question contains answers that are really good, but I want to add one thing: "*[...] he told me we use them when we want to take the ownership of a resource*" - that's incorrect. `std::weak_ptr` is not meant to take the ownership. It's essentially a non-owning pointer that, when properly used, can easily prevent the dangling-pointer situation. – Fureeish Jun 07 '19 at 12:57

0 Answers0