You cannot use weak_ptr
s as keys unless you use a owner based comparison (against the value based one, that is not even defined for weak_ptr, for which trying to use the operator< results in an error).
The problem is that they can expire and the ordering of your containers (a set
as well as a map
) wouldn't be consistent anymore.
As correctly pointed out by Kerrek SB (forgive me, but the mobile app does not let me to correctly link users) and as you can read from my link in the comments, you can rely on std::owner_less
starting from C++11.
A valid approach is to use a set
defined as it follows:
std::set<std::weak_ptr<C>, std::owner_less<std::weak_ptr<C>>>
Note that owner_less
can be less verbose, for it deduces the type automatically.
Keep in mind that this approach does not keep you from invoking the expired
method while visiting the set
, because it can still contains expired objects even if consistently ordered.
Also, note that there is a huge difference between an expired weak_ptr
and an empty one, so the owner based comparison could be not so intuitively, even if expiration shouldn't affect it once used the approach above mentioned.
Here some links.