2013-03-26 44 views
1

我對共享指針是完全新聞。我試圖做我怎樣才能設置一個共享指針到一個普通指針

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

初始化之一,但它說,它需要一個類型說明符....我也想這個共享指針設置爲 一個普通指針。任何人都可以解釋我是如何工作的。非常感謝

#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; 
} 

};

回答

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

應該

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

或任何你的構造看起來像

正從shared_ptr的

setPen(pen.get()); 

提示原始指針:小心設置被控制的原始指針通過智能指針。你確定你不想傳遞一個智能指針(共享或唯一)嗎?

你也應該通過STD輔助函數創建共享指針

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

我不太明白。 http://msdn.microsoft.com/en-us/library/windows/desktop/ms534485%28v=vs.85%29.aspx說,有兩個參數 - 哪個當然需要傳遞給構造函數 – Daniel 2013-03-26 22:42:03

+0

錯誤C2039:'shared_ptr':不是'std'的成員 錯誤C2143:語法錯誤:缺少';'之前'<' 錯誤C4430:缺少類型說明符 - 假定爲int。注意:C++不支持default-int – user1665569 2013-03-26 22:50:09

+0

這些是我得到的錯誤,是的,我正在做的包括。當我只有std :: shared_ptr 筆;我沒有錯誤... – user1665569 2013-03-26 22:51:03

0

使用get從shared_ptr的把它作爲一個原始指針:

setPen(pen.get()); 

但要確保你不會存儲它在setPen中。那會在以後導致討厭的錯誤。

+0

pen.get()= pen2?那將不起作用 – user1665569 2013-03-26 22:40:55

+0

不能分配給pen.get() – 2013-03-26 22:43:49