How does std::weak_ptr help in solving the circular dependency problem, and what happens internally when you call .lock() on it?

Last updated 21 June 2026

  • std::weak_ptr is a non-owning observer that doesn't add to the strong count. Making one side of an A↔B shared_ptr cycle weak lets both be destroyed.

  • lock() checks the control block's strong count. If it is above 0 it atomically increments it and returns a valid shared_ptr, otherwise it returns an empty one.

  • The weak count keeps the control block (not the object) alive, so expired() and lock() stay safe to call.

  • https://utkrusht.ai/blog/cplusplus-interview-questions
  • https://roadmap.sh/questions/cpp
  • https://internshala.com/blog/cpp-coding-interview-questions/
All C++ interview questions