You cannot insert a temporary shared_ptr into a set of weak pointers because it is a memory leak in the sense that this stored weak pointer points to already deleted memory.
intset.insert(make_shared<int>(1));
This is why you cannot find it in the set, because *lhs.lock() is UB here.
See weak_ptr :: lock doc .
You need to make your Γ²rder statement as follows:
struct lex_compare { bool operator() (const weak_ptr<int> &lhs, const weak_ptr<int> &rhs)const { auto lptr = lhs.lock(), rptr = rhs.lock(); if (!rptr) return false;
All this means that you need to have this shared_ptr in order to calculate it:
int main(){ set<weak_ptr<int>,lex_compare> intset; auto shared1 = make_shared<int>(1); intset.insert(shared1); cout << "intset size:" << intset.size() << endl;
With the above - your account will work.
Also consider that shared_ptr in the set ...
[UPDATE]
marko in the comments pointed to a valid problem. std :: weak_ptr cannot be used as a key the way you use it. Only if you can guarantee that the specified value will never change, and the pointer itself will never expire. See this example:
set<weak_ptr<int>,lex_compare> intset; auto shared1 = make_shared<int>(1); intset.insert(shared1); cout << "Does 1 exist?"<< intset.count(make_shared<int>(1))<<endl;
And another example:
set<weak_ptr<int>,lex_compare> intset; auto shared1 = make_shared<int>(1); intset.insert(shared1); cout << "Does 1 exist?"<< intset.count(make_shared<int>(1))<<endl;
You can save std :: shared_ptr, which prevents the pointer from expiring - and std :: shared_ptr has operator < - but this operator compares the pointers themselves and not the default values, so std::set<std::shared_ptr<int>> better std::set<std::shared_ptr<int>> - but the best would be std::set<int>
Or change std::set<...> β std::vector<std::weak_ptr<int>> - and use count_if - see:
vector<weak_ptr<int>> intset; auto shared1 = make_shared<int>(1); intset.push_back(shared1); cout << "Does 1 exist?"<< count_if(begin(intset), end(intset), [](auto&& elem) { auto ptr = elem.lock(); return ptr && *ptr == 1; });
Or using std::set<std::shared_ptr<int>> :
set<shared_ptr<int>> intset; auto shared1 = make_shared<int>(1); intset.insert(shared1);