Search code examples
c++pointersshared-ptr

How can I set a shared pointer to a regular pointer


I'm completely news to shared pointers. I'm trying to initialize one by doing

std::shared_ptr<Gdiplus::Pen> pen(new Gdiplus::Pen);

but it says that it needs a type specifier.... I am also trying to set this shared pointer to a regular pointer. Can anyone explain me how this works. Much appreciated

#pragma once
class Shape
{
public:
Shape();
Gdiplus::Point start;   
Gdiplus::Point end;

std::shared_ptr<Gdiplus::Pen> pen(new Gdiplus::Pen());
virtual  LRESULT Draw(Gdiplus::Graphics * m_GraphicsImage) = 0;


void setPen(Gdiplus::Pen * pen2) {

    pen.get() = pen2; 
}
void setStart(int xPos, int yPos) {
    start.X = xPos;
    start.Y = yPos;
}
void setEnd(int xCor, int yCor) {
    end.X = xCor;
    end.Y = yCor;
}

};


Solution

  • std::shared_ptr<Gdiplus::Pen> pen(new Gdiplus::Pen);
    

    should be

    std::shared_ptr<Gdiplus::Pen> pen(new Gdiplus::Pen(brush, width));
    

    or whatever your constructor looks like

    getting a raw pointer from shared_ptr

    setPen(pen.get());
    

    hint: be careful with setting raw pointers which are controlled by smart pointers. are you sure that you don't want to pass a smart pointer (shared or unique)?

    you should also create your shared pointer through the std helper function

    auto pen = std::make_shared<Gdiplus::Pen>(brush, width);