I have the following setter and getter which gives me raw pointers. These could be accessed from different threads as well.I want to make m_pObj a shared pointer- - std::shared_ptr<(IMyInterface> m_pObj;
Code was like this. If m_obj is not null i have to release and assign the new pointer in SetPointer
void MyClass::SetPointer(IMyInterface* pObj)
{
EnterCriticalSection(&cs1)
if (NULL != m_pObj)//Member variable to hold the incoming pointer
{
m_pObj>Release();
m_pObj= NULL;
}
m_pObj= pObj;
if (NULL != m_pObj )
{
m_pObj->AddRef();
}
LeaveCriticalSection(&cs1)
}
IMyInterface* MyClass::GetPointer()
{
EnterCriticalSection(&cs1)
if (NULL != m_pObj)
{
m_pObj->AddRef();
}
LeaveCriticalSection(&cs1)
return m_pObj
}
Modified - setter
void MyClass::SetPointer(IMyInterface* pObj)
{
if (NULL != m_pObj)
{
m_pObj->Release();
m_pObj= NULL;
}
m_pObj = std::shared_ptr<IMyInterface>(pObj));
}
While accessing the getter in another class it should increase the reference count as well,for shared pointer,I think I just have to assign it to the local shared pointer rit?Would it automatically increase the reference count?
std::shared_ptr<IMyInterface> MyClass::GetPointer()
{
return m_pObj;
};
accessing from other place
std::shared_ptr<IMyInterface> pObj1 = GetPointer();//hope it would increase th reference count
Both the functions could be accessed from different threads-its possible the the in other places the getter is called and before I do addref the setter called from different thread and released it,so was the CS for.In this case is it needed?Is the modified one OK?
Aucun commentaire:
Enregistrer un commentaire