Search code examples
c++pointersshared-ptr

how can you see if shared pointers are equal to each other


i'm trying to implement a Flyweight design in c++. This is what I have so far.

std::unordered_map<std::pair<Gdiplus::Color, float>, std::shared_ptr<Gdiplus::Pen>> mymap;
std::shared_ptr<Gdiplus::Pen> getPen(Gdiplus::Color const & color, float width )
{   
    std::pair<Gdiplus::Color,float> input;
    input = std::make_pair(color, width);
    std::unordered_map<std::pair<Gdiplus::Color, float>, std::shared_ptr<Gdiplus::Pen>>::const_iterator got = mymap.find (input);

        if ( got == mymap.end() )
        {
            auto pen = std::make_shared<Gdiplus::Pen> ();
            pen->SetColor(color);
            pen->SetWidth(width);
            //std::pair<Gdiplus::Color,float> input2;
            mymap.insert(std::make_pair(input, pen));
            return pen;             
        }       
        else
        {
            if (std::shared_ptr<Gdiplus::Pen> m_pen = got->second.get())
               return m_Pen;
        }

}

My issue is in the else statement. i'm trying to figure out if both pointers are the same but i get an error saying

cannot convert from 'Gdiplus::Pen *' to 'std::tr1::shared_ptr<_Ty>' 

Solution

  • Your problem lines in this line:

    std::shared_ptr<Gdiplus::Pen> m_pen = got->second.get();
    

    Explanation:

    std::shared_ptr<T>.get() returns the internal pointer stored by a shared_ptr (i.e., Grdiplus::Pen*). Try this instead:

    std::shared_ptr<Gdiplus::Pen> m_pen = got->second;
    

    This will allow you to assign to m_pen, since there is no implicit conversion from T* to std::shared_ptr<T>.