Somebody use shared pointer to ensure that the aforementioned handle are destroyed when it's no longer needed.
In practice, the implementation of InitDemoStruct()
DestroyStruct()
struct DemoStruct
are opaque to me.They are provided by others.
Although this code snippet works as expected, but it looks strange indeed:
It's commonly seen that a smart pointer points to a specific class or struct, e.g: std::shared_ptr<struct DemoSt> ptr2object
; Recently, I saw such usage. Use smart pointer to pointer to a pointer of a specific class or struct, e.g:std::shared_ptr<struct DemoSt*> ptr2point_of_object
;
UPDATED: There is an answer provided by nwp
.
Here is the aforementioned code snippet:
#include <memory>
#include <iostream>
struct DemoStruct;
using DemoStructHandle = DemoStruct* ;
//In practice, the implementation of `InitDemoStruct()` `DestroyStruct()` `struct DemoStruct` is opaque to me.
//They are provided by others.
struct DemoStruct{
};
void InitDemoStruct(DemoStructHandle* handle_ptr){
*handle_ptr = new DemoStruct();
//may do some other meaningful init in InitDemoStruct();
};
void DestroyStruct(DemoStructHandle* handle_ptr){
std::cout << "Destroy() is called" << std::endl;
if(handle_ptr==nullptr){
return;
}
delete *handle_ptr;
}
//I use shared pointer to ensure that the aforementioned handle is destroyed when it's no longer needed.
std::shared_ptr<DemoStructHandle> MakeDemoStructHandlePtr(void)
{
return std::shared_ptr<DemoStructHandle>(new DemoStructHandle(nullptr), [](DemoStructHandle* pHandle){
DestroyStruct(pHandle);
delete pHandle;});
}
int main()
{
std::shared_ptr<DemoStructHandle> demo_class_handle_ptr = MakeDemoStructHandlePtr();
InitDemoStruct(demo_class_handle_ptr.get());
}
Aucun commentaire:
Enregistrer un commentaire