Skip site navigation (1)Skip section navigation (2)
Date:      Tue, 22 May 2007 16:56:26 +0000
From:      "Poul-Henning Kamp" <phk@phk.freebsd.dk>
To:        Warner Losh <imp@bsdimp.com>
Cc:        cvs-src@freebsd.org, src-committers@freebsd.org, rwatson@freebsd.org, cvs-all@freebsd.org, bde@optusnet.com.au
Subject:   Re: cvs commit: src/lib/libmemstat memstat_malloc.c 
Message-ID:  <13451.1179852986@critter.freebsd.dk>
In-Reply-To: Your message of "Tue, 22 May 2007 10:20:45 CST." <20070522.102045.112563319.imp@bsdimp.com> 

next in thread | previous in thread | raw e-mail | index | archive | help
In message <20070522.102045.112563319.imp@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@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.



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?13451.1179852986>