c++ - Is it safe to store a changing object in a stl set? -
i want container store unique std::weak_ptrs. std:set requires operator<, presumably because stores items in tree. worry if implement operator< in obvious way (destroyed ptr = null ptr < valid ptr) result can mutate after items added container, may break it.
is in fact safe? if not, suggestions container?
thanks
you cannot use weak_ptr
s keys unless use owner based comparison (against value based one, not defined weak_ptr, trying use operator< results in error). problem can expire , ordering of containers (a set
map
) wouldn't consistent anymore.
as correctly pointed out kerrek sb (forgive me, mobile app not let me correctly link users) , can read link in comments, can rely on std::owner_less
starting c++11.
a valid approach use set
defined follows:
std::set<std::weak_ptr<c>, std::owner_less<std::weak_ptr<c>>>
note owner_less
can less verbose, deduces type automatically.
keep in mind approach not keep invoking expired
method while visiting set
, because can still contains expired objects if consistently ordered.
also, note there huge difference between expired weak_ptr
, empty one, owner based comparison not intuitively, if expiration shouldn't affect once used approach above mentioned.
Comments
Post a Comment