This is example demonstrates that we are in-general fighting hard against
C++... up-hill both ways in a blizzard.  :)  This is why starting with zero
features and working our way up with a white list gives examples of correct
usage.  It looks like a lot of GDAL development happens by
copy-paste-tweak, so good examples are key.  And for every issue, we have
solutions that are valid C/C++03/C++11/C++14... the best solution is not
necessarily in any particular one.


> If we move to a later C++ standard, or even use features of C++98 we
> currently
> don't use, I'd advocate for using things that are obviously making the code
> better / more readable. Honestly who finds that
> "std::unique_ptr<int *, std::function<void(char *)>> Vals(CPLCalloc(256,
> 0),
> CPLFree);" is obviously more readable, efficient and less error prone than
> "std::vector Vals(256,0)" ?
>
>
This is cart before the horse but... as fast as I can so expect typos.  Now
just think of a ~1K long function or method with tons of instances and lots
of places to bailout successfully or as failures.  We have > 9K
free/CPLFree/CPLdelete/CPLDestroys that could be < ~100.

GDALMyBigObj *poInstance = CPLCalloc(sizeof(GDALMyBigObj);
...
if (oops) {
   CPLDelete(poInstance)
   return;
}
...
return;  // kaboom
...
if (oops) {
   CPLDelete(poInstance)
   return;
}
...
if (oops) {
   CPLDelete(poInstance)
   return;
}

CPLDelete(poInstance)
return;

or worse

GDALMyBigObj *poInstance = CPLCalloc(sizeof(GDALMyBigObj);
...
if (oops) {
   goto END;
}
...
// Careful what you do here because you are crossing gotos.
...
if (oops) {
   goto END;
}
...
if (oops) {
   goto END;
}
...
END:
CPLDelete(poInstance)
return;

when you could have...  And yes, getting to this is not trivial.  There are
multiple things here to discuss:

auto poInstance = std::make_unique<GDALMyBigObj>(arg1, arg2, arg3);

if(oops)
  return;  // Everything cleaned up nice
...

if(oops)
  return;  // Everything cleaned up nice
...

if(oops)
  return;  // Everything cleaned up nice
...

return;  // Woohoo!  Success!

My example of the deleter comes from real code where I don't what a heap
checker barfing at me when ever a test fails.  Makes writing and debugging
tests insane....

// Apache 2.0 license...

{
  // ...
  unique_ptr<OGRFeature> feature(layer->GetNextFeature());
  OGRGeometry *geometry = feature->GetGeometryRef();
  ASSERT_NE(nullptr, geometry);

  char *wkt_tmp = nullptr;
  ASSERT_EQ(OGRERR_NONE, geometry->exportToWkt(&wkt_tmp));
  std::unique_ptr<char, CplFreeDeleter> wkt(wkt_tmp);

  wkt_tmp = nullptr;
  ASSERT_STREQ("POINT (-109.27 10.3)", wkt.get());

}
_______________________________________________
gdal-dev mailing list
gdal-dev@lists.osgeo.org
http://lists.osgeo.org/mailman/listinfo/gdal-dev

Reply via email to