How does std::weak_ptr help in solving the circular dependency problem, and what happens internally when you call .lock() on it?
Last updated
std::weak_ptris a non-owning observer that doesn't add to the strong count. Making one side of an A↔Bshared_ptrcycle 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 validshared_ptr, otherwise it returns an empty one.The weak count keeps the control block (not the object) alive, so
expired()andlock()stay safe to call.