jeudi 10 février 2022

How to assign the shared_ptr object to the function of type raw pointer using C++

I am creating the shared_ptr in a function and returning raw pointer from that function. To get the underlying raw pointer from the shared_ptr I am using .get()

If i am using the raw pointer in a function and assigning to the function of type raw pointer it is working without any issue. But if i create the shared_ptr and while returning, it is calling the destructor and deleting the memory assigned to the object and crashing.

How to assign the shared_ptr object to the function of type raw pointer?

CMyClass::CMyClass()
{
}

CMyClass::~CMyClass()
{
}

CMyClass* CreateClassInstance()
{
std::shared_ptr<CMyClass> l_MyClassInterface = std::make_shared<CMyClass>();
return l_MyClassInterface.get();
}

CMyClass* CreateClassInstance()
{
CMyClass* l_MyClassInterface = new CMyClass();
return l_MyClassInterface;
}

auto l_pMyClassInterface = CreateClassInstance();

Aucun commentaire:

Enregistrer un commentaire