mardi 29 août 2017

Can I safely use GDAL with shared_ptr instead of Create/Destroy functions?

I am creating a shapefile in C++ 11 using GDAL.

Can I can safely make use of shared_pt< SomeGDALType > instead of SomeGDALType::CreateSomeGDALType() and SomeGDALType::DestroySomeGDALType(); ?

I noticed that the example code follows this pattern for all pointers the library needs:

OGRFeature *poFeature
poFeature = OGRFeature::CreateFeature( poLayer->GetLayerDefn() )

... other code that calls library function with above pointer ...

OGRFeature::DestroyFeature( poFeature );
//end of function.

Since I want my pointers to always be cleaned up nicely, I want to use a shared pointer like so:

std::shared_ptr<OGRFeature>poFeature(new OGRFeature(poLayer->GetLayerDefn()));

... other code that calls library function with poFeature.get() ...

//end of function

This obviates the problem of memory leaks if my code throws an exception. My code compiles, runs and creates a working shapefile.

My question is twofold:

Firstly; Is there a specific reason I want the memory to be allocated and de-allocated specifically by the library, (thereby allocating it possibly on another heap) which is what happens when I call the example's create and destroy functions?

Secondly; Can problems, beyond obvious programming mistakes on my end, arise as a result of my proposed alternative implementation?

Aucun commentaire:

Enregistrer un commentaire