As people already stated in the comments, you can not do that. A shared_ptr
always owns a reference, while a weak_ptr
never does. The API of the standard library is explicitly designed in a way that the type tells you whether you currently own a reference or not (and the only thing you should do to access pointees of weak_ptr
objects is lock()
them, and check the resulting shared_ptr
for non-null-ness, so you can (even in a multi-threaded environment) be sure, that you own a reference for yourself while working with the object.
What you could possibly do is have a map of weak_ptr
all along, and store a shared_ptr
elsewhere as long as you want to keep the object alive. Depending on the design or purpose, the place for the shared_ptr
might even be a member variable of the object.
If you use a map of pairs, I would not swap() the pair members, but start with a pair of a shared and a weak ptr referring to the same managed object, and just reset() the shared ptr if it is decided to drop the strong reference, not touching the weak_ptr at that point.