cvs commit: src/lib/libmemstat memstat_malloc.c

Poul-Henning Kamp phk at phk.freebsd.dk
Tue May 22 16:56:09 UTC 2007


In message <20070522.102045.112563319.imp at bsdimp.com>, Warner Losh writes:

>> > Should know better than to use __DECONST: C programmers.
>
>Zen Master bde hits.  You are confused.  You are Dazed.--More--
>You have received enlightment.  Welcome to level 34583.

Actually, I'm not sure I made it.

Const is a very useful construct, both for the compilers ability
to generate good code and for the programmer to express his intention,
but the simplicity of the const concept in C means that it is less
useful than it could be, unless __DECONST and similar are (ab)used.

Take a simple example:

	struct foo {
		...
	};

	struct foo *create_foo(args, ...);
	void destroy_foo(struct foo *);

Nothing outside these two functions should modify, reassign or otherwise
muck about with the contents of a struct foo.

In an ideal world, I would have two versions of struct foo: one where all
members are const and one where they are not, and compiler would realize
that a cast from the R/W to the R/O variant is a safe operation, so that
create_foo() could be written in terms of and return the R/O variant

How to do the destroy_foo() needs a different trick, since we are
not modifying the fields, we are destroying them, so the needed information
here is custody information:
	void destroy_foo(struct foo * __custody);
which tells the compiler that the pointer and what it pointed to
is not valid after a call to destroy_foo().

C unfortunately lacks a syntax that can express suck subtle and
non-subtle nuances and recent standardization efforts have shown
little interest in offering more "intentional programming" facilities
in C.

Absent such progress and despite what the Zen master says, I think
const is a useful concept and that the occational well-thought out
use of __DECONST() can not only be fully justified but also
recommended.  Provided it is used to improve the expression of
deliberate intent, rather than to paste over gottchas.

-- 
Poul-Henning Kamp       | UNIX since Zilog Zeus 3.20
phk at FreeBSD.ORG         | TCP/IP since RFC 956
FreeBSD committer       | BSD since 4.3-tahoe    
Never attribute to malice what can adequately be explained by incompetence.


More information about the cvs-src mailing list