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();
CodePudding user response:
Yes, what @user17732522 said.
In the code as written, l_MyClassInterface
is going out of scope when your first version of CreateClassInstance
returns, taking your newly created object with it. When you return a shared_ptr
, as opposed to the pointer returned by get()
, the mechanism that it uses to keep track of the reference count for your object kicks in and stops that from happening. (Well, in principle. In practise, copy elision usually / always ensures that the shared_ptr
created by make_shared
is returned directly to the caller, but that's a detail.)
The other (inferior) solution would be to return the pointer returned by new
directly and assign it to a shared_ptr
in the caller. But that is error-prone, and not recommended.