I have shared_ptr variable in my class object (ObjA). There is a requirement where this object is to be stored as (void*) entity of another Class' object (ObjB).
My question is, what will be the behaviour of shared_ptr (will associated heap memory be freed?, what will happen to its reference count?)-
when ObjA is converted to void*
when void* entity of ObjB is cast back to (ClassA *)
Simplified Code:
Class AA{
shared_ptr<int> aptr;
public:
AA(){
aptr = make_shared<int>(100);
}
shared_ptr<int> get_aptr(){
return aptr;
}
};
Class BB{
void *smpl;
public:
void setter(void* p){
smpl = p;
}
void* getter(){
return smpl;
}
};
int main(){
AA *objA = new AA();
BB *objB = new BB();
objB->setter(objA);
//status of allocated int in class AA here?
//some code later
AA *objA_2 = (AA*)objB->getter();
//status of allocated int in class AA here?
shared_ptr<int> p2 = objA_2->get_aptr();
//is this allowed
}
My prime concern is- how to deallocate the memory of shared_ptr. (Given it is enclosed in void* object, which can not be deleted- shared_ptr remains in scope at all times) I tried to delete objB, with appropriate casting to its component void* in destructor-
BB::~BB(){
delete (*AA)smpl;
}
but this is giving error as shared_ptr variable in class AA does not allows explicit delete- it frees its allocated area only when it goes out of scope. (In this case, it never knows when it goes out of scope!)
Also, class BB is a third party class- I cant modify the type void* of smpl member variable (_userData variable in Node class, in Cocos2dx). Please help to resolve this memory leak..