[gdal-dev] Casting poDS, in IReadBlock and similar places

Even Rouault even.rouault at spatialys.com
Tue May 23 04:28:56 PDT 2017


On mardi 23 mai 2017 11:40:08 CEST Andrew C Aitchison wrote:
> I see that in http://www.gdal.org/gdal_drivertut.html the function
> JDEMRasterBand::IReadBlock has
>       JDEMDataset *poGDS = static_cast<JDEMDataset *>(poDS);
> (this is a change from gdal-2.1.3 and earlier where
> frmts/jdem/jdemdataset.cpp has
>              JDEMDataset *poGDS = (JDEMDataset *) poDS;
> ).
> 
> However, I see that amongst other 2.2.0 drivers, reinterpret_cast
> is more common than static_cast and the dods driver has dynamic_cast:
> 
> My C++ is 25 years old and self taught, so I am still learning when to
> use static_cast, dynamic_cast and reinterpret_cast (and const_cast).
> 
> Can anyone more familiar with modern C++ guide me ?

In all those cases static_cast can be used. There have been a first pass of conversion from C 
style cast to C++ one using reinterpret_cast which is the equivalent of C style cast (it allows 
to cast virtually anything to anything). But we realized later it was a bit too lax and static_cast 
is a better fit when casting from parent to derived class. Both will result in the same code as 
there's no multiple inheritance in dataset class hierarchy (using reinterpret_cast would lead 
to runtime crashes in that case). So static_cast is always safer in those cases.

We could also use dynamic_cast but as we are sure about the target type of cast, this is a bit 
overkill. The occurence in DODS could/should be replaced by a static_cast.

Even

-- 
Spatialys - Geospatial professional services
http://www.spatialys.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.osgeo.org/pipermail/gdal-dev/attachments/20170523/5481fcef/attachment.html>


More information about the gdal-dev mailing list