Search code examples
c++stlc++11weak-ptr

Comparator operator in weak_ptr C++


I am still a novice in the new stl members.Can anyone point out why this code is giving segmentation fault?

#include<memory>
#include<stdio.h>
#include<map>
#include<set>
#include<string>
using namespace std;
struct StubClass
{
    weak_ptr<string> b;
    int c;
    friend bool operator==(StubClass x,StubClass y);
    friend bool operator<(StubClass x,StubClass y);
    StubClass(weak_ptr<string> x):b(x){c=5;}    
};
bool operator==(StubClass d,StubClass c) { return d.b==c.b;}
bool operator<(StubClass d,StubClass c) { return d.b<c.b; }


int main()
{
    shared_ptr<string> spPtr(new string("Hello"));
    weak_ptr<string> wpPtr(spPtr);
    StubClass hello(wpPtr);
    set<StubClass> helloSet;
    helloSet.insert(hello);
    if(helloSet.find(StubClass(wpPtr))!=helloSet.end()) printf("YAYA");
    else puts("Bye");
}

The error is in line

if(helloSet.find(StubClass(wpPtr))!=helloSet.end()) printf("YAYA");

More research reveals there is a problem when the StubClass's comparator function is called. I am compiling the program here

EDIT:

bool operator==(StubClass d,StubClass c) { return d.b.lock()==c.b.lock();}
bool operator<(StubClass d,StubClass c) { return d.b.lock()<c.b.lock(); }

This resolved the issue.I should be reading more.:( Anyways can anyone from the community explain the reason why the first code gives SIGSEGV.I figured it out eventually,but still a nice explanation won't hurt. :)


Solution

  • If you want to compare strings stored in weak_ptr do this:

    bool operator<(StubClass d, StubClass c) 
    {
        std::shared_ptr<std::string> a = d.b.lock();
        std::shared_ptr<std::string> b = c.b.lock();
    
        if (!a && !b)
            return false; 
    
        if (!a)
            return true;
    
        if (!b)
            return false;
    
        return *a < *b;
    }
    

    Run result