Sujet : Re: So You Think You Can Const?
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.lang.cDate : 08. Jan 2025, 21:12:37
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <86frlt83pm.fsf@linuxsc.com>
References : 1 2 3 4 5
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Julio Di Egidio <
julio@diegidio.name> writes:
[...]
Say my program unit implements AVL trees, with (conceptually
speaking) constructors/destructors, navigation and retrieval, and
of course manipulation (inserting, deleting, etc.).
>
My idea (but I would think this is pretty "canonical" and, if it
isn't, I am missing the mark) is: my public functions take/give
"sealed" instances (with const members to const data), as the user
is not supposed to directly manipulate/edit the data, OTOH of
course my implementation is all about in-place editing...
A better choice is to put the AVL code in a separate .c file,
and give out only opaque types to clients. For example (disclaimer:
not compiled):
// in "avl.h"
typedef struct avl_node_s *AVLTree;
// note that the struct contents are not defined in the .h file
... declare interfaces that accept and return AVLTree values ...
// in "avl.c"
#include "avl.h"
struct avl_node_s {
// whatever members are needed
};
... implementation of public interfaces and any supporting
... functions needed
I might mention that some people don't like declaring a type name
that includes the pointerness ('*') as part of the type. I think
doing that is okay (and in fact more than just okay; better) in the
specific case where the type name is being offered as an opaque
type.
Of course you could also make the opaque type be a pointer to a
'const' struct type, if you wanted to, but the extra "protection" of
const-ness doesn't add much, and might actually cost more than it
buys you because of the additional casting that would be needed.