C++ API Uses 'const' Member Functions Gratuitously


#1

The HDF5 C++ API declares many member functions const even though they allow the state, contents and data associated with the C++ object to be modified. While this is acceptable in limited situations, such as reference counting, it defeats the purpose of having const member functions, and it reduced the value that could be added by the C++ API to the underlying C API. For example, in H5::DataSpace, it makes sense for the get...() member functions to be const because they simply return the current state of the object, but it does not make sense for the select...() members to be const because they modify the state of the object. If I pass a const H5::DataSpace to another C++ function, I would expect its constness to be respected and for the selection associated with its underlying C hid_t to be immutable without the use of const_cast<>. This is currently not the case, and a const HDF5 C++ object can be modified as if it were mutable, which defeats a valuable compile-time safeguard provided by the C++ language. The same goes for H5::DataSet::extend() and most of the API, where functions are incorrectly labeled const. Fixing this issue would require const to be removed from many C++ member functions, but fortunately the impact of removing const is not as severe as adding const to existing routines.


#2

Try this alternative library, which makes C++ look good again. However in the following H5CPP function prototype you notice the const qualifier for all arguments:

h5::fd_t h5::gcreate( const h5::fd_t | const h5::gr_t, const std::string& name
            [, const h5::lcpl_t& lcpl] [, const h5::gcpl_t& gcpl] [, const h5::gapl_t& gapl]);

meaning that the passed arguments (within the function body) won’t follow this pattern borrowed from cppreference.com:

const int n = 1; // object of const type
n = 2;           // error: the type of n is const-qualified

and doesn’t imply that the internal state of h5::fd_t is not modified. In fact the passed h5::fd_t is just an int type, same as the example above, binary compatible/identical with the CAPI hid_t which is the traditional way to decouple file system implementation details from a public API.