Const Ideas

Walter Bright newshound1 at digitalmars.com
Sun Dec 2 23:36:20 PST 2007


Janice Caron wrote:
> const(X) must mean the same thing as const X, for all X. Unless you
> have that, there will always be complaints.

Let's look at it another way. Consider a class C:

    alias const(C) CC;
    void foo(CC c, CC f)
    {
	auto d = c;
	d = f;
    }

This kind of code can be expected, and it should work. It should also 
work if CC is:

     alias const(int) CC;

because this can happen with metaprogramming. The insight is that, 
although a type can be const, it can always be copied (shallow copy) 
without affecting the const. If a variable is bound to a const type, 
being able to rebind it doesn't affect the const'ness, because it's just 
another copy. In other words, const'ness of types, const-correctness, 
etc., *only matters* for a type with references in it. You cannot 
undermine const-correctness by rebinding a variable that is typed as const.

Next, a storage class says something about how the variable is stored, 
not its type. We'd like to be able to say a variable is stored in 
read-only memory (even if that is only conceptual). Hence, we'd like to 
give it a storage class 'const' to put it in read-only memory. Pulling 
on that string, in order to have transitive const, using a const storage 
class must also make the type of the variable const, too.

Thus, we have:

	const(T) x;

which types x as having a const type, which matters only for references, 
and:

	const T x;

which types x as having a const type, *and* (conceptually) puts x in 
read-only memory after it is initialized.

I suggest writing some actual code using const. I think you'll find it 
is rather natural in practice. For example, nobody is going to write:

	const(int) x = 3;

when they want a compile-time constant, they'll write:

	const int x = 3;

The only time you'll see the form:

	const(T) x;

is when T is a reference type, or is an unknown type that could be a 
reference type. And the only reason one would write this is to protect 
the references, not x itself.

The natural question then, is why have:

	const(int) x;

at all? The reason is when one is deconstructing types using templates, 
and then reconstructing them, the const-correctness of what is being 
referred to must be carried along, else the const-correctness is lost.



More information about the Digitalmars-d mailing list