質問

i have map that looks like this:

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

now i try to set this map with elements via fucntion like this:

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

i just call it like this :

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

PuzzleObj contains memeber from type IImageComponent *
PuzzleObj inherits from base class

but it give me error like this :

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>          ]
役に立ちましたか?

解決

std::make_shared<PuzzleObj> creates a new PuzzleObj for you. What you need is std::shared_ptr<PuzzleObj>(puzzleObj).

More importantly

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

should be declared as:

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

because it shares ownership of puzzleObj by storing it in the container and that must be communicated in function's interface.

And call it like so:

std::shared_ptr<PuzzleObj> pPuzzleObjStickLeft(std::make_shared<PuzzleObj>());
pComponentMadiator->Register(1, pPuzzleObjStickLeft);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top