std :: make_shared给出错误,我不明白

时间:2014-02-16 12:55:57

标签: c++ shared-ptr

我的地图看起来像这样:

typedef std::map<PuzzlePartLocation, std::shared_ptr<PuzzleObj>> ComponentsMap;

现在我尝试通过这样的元素设置这个地图:

void ComponentMadiator::Register(const PuzzlePartLocation puzzlePartLocation,PuzzleObj* puzzleObj)
{
   componentsMap[puzzlePartLocation] = std::make_shared<PuzzleObj>(puzzleObj);
}

我只是这样称呼它:

 PuzzleObj* pPuzzleObjStickLeft = new PuzzleObj()
pComponentMadiator->Register(1,pPuzzleObjStickLeft );

PuzzleObj包含来自IImageComponent *的类型的memeber PuzzleObj继承自基类

但它给我这样的错误:

1>c:\program files\microsoft visual studio 11.0\vc\include\memory(873): error C2664: 'PuzzleObj::PuzzleObj(IImageComponent *)' : cannot convert parameter 1 from 'PuzzleObj *' to 'IImageComponent *'
1>          Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>          c:\program files\microsoft visual studio 11.0\vc\include\memory(972) : see reference to function template instantiation 'std::_Ref_count_obj<_Ty>::_Ref_count_obj<PuzzleObj*&>(_V0_t)' being compiled
1>          with
1>          [
1>              _Ty=PuzzleObj,
1>              _V0_t=PuzzleObj *&
1>          ]
1>          c:\program files\microsoft visual studio 11.0\vc\include\memory(972) : see reference to function template instantiation 'std::_Ref_count_obj<_Ty>::_Ref_count_obj<PuzzleObj*&>(_V0_t)' being compiled
1>          with
1>          [
1>              _Ty=PuzzleObj,
1>              _V0_t=PuzzleObj *&
1>          ]
1>          d:\dev\cpp\cocos2d-x\cocos2d-x-3.0beta2\cocos2d-x-3.0beta2\projects\neonbreaker\classes\componentmadiator.cpp(23) : see reference to function template instantiation 'std::shared_ptr<_Ty> std::make_shared<PuzzleObj,PuzzleObj*&>(_V0_t)' being compiled
1>          with
1>          [
1>              _Ty=PuzzleObj,
1>              _V0_t=PuzzleObj *&
1>          ]

1 个答案:

答案 0 :(得分:1)

std::make_shared<PuzzleObj>为您创建新的PuzzleObj。你需要的是std::shared_ptr<PuzzleObj>(puzzleObj)

更重要的是

void ComponentMadiator::Register(const PuzzlePartLocation puzzlePartLocation,PuzzleObj* puzzleObj);

应声明为:

void ComponentMadiator::Register(const PuzzlePartLocation puzzlePartLocation, std::shared_ptr<PuzzleObj> const& puzzleObj);

因为它通过将其存储在容器中来共享puzzleObj的所有权,并且必须在函数的界面中进行通信。

并称之为:

std::shared_ptr<PuzzleObj> pPuzzleObjStickLeft(std::make_shared<PuzzleObj>());
pComponentMadiator->Register(1, pPuzzleObjStickLeft);