"invariant" vs. "const"

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 5 15:15:34 PST 2009


On Thu, 05 Nov 2009 17:58:35 -0500, AJ <aj at nospam.net> wrote:

> A. String literal in D (not zero-terminated, immutable):
>
>     invariant(char)[] lit = "abc";

Actually, string literals are zero-terminated for easy passing to a C  
function that requires it.  Think of a string literal like this:

"abc" => "abc\0"[0..$-1]

The zero is still there, just not inside the array that's returned.  I  
think toStringz takes advantage of this, but I'm not sure.

> B. String literal in C++ (zero-terminated, immutable):
>
>     const char* lit = "abc";  // "const" here is redundant?
>
> C. const array of characters in C++ (zero-terminated, mutable if const is
> cast away):
>
>     const char[] lit = "abc";
>
> (Aside: I'm not sure if C is a good replacement for B or if it was even
> intended to be so.)

I think it's just syntax sugar, it's not a different type.  and I think  
you can not put the const, and the literal is *not* a unique copy of the  
data.  The same issue happens in D1.

> I'm not sure how to think about "invariant". I think that "const" is
> overloaded so much in C++ that it leads to confusion. I think the answer
> lies somewhere in the distinctions between "const storage class" and  
> "const
> type", of which "invariant is the former?

invariant as a type modifier => will not ever change
const as a type modifier => cannot be changed through this alias, but may  
change through another.

invariant or const as a storage class => manifest constant.

The differences are subtle.  You can have invariant data that was once  
mutable, but you must ensure as the developer that there are no mutable  
aliases to that data.  The compiler cannot help you in that regard.  It's  
one of the shortcomings of the const scheme in D (but it's still better  
than C++).

As a type modifier, const is the unification of both invariant and mutable  
-- both can be implicitly cast to const.  Therefore, if you want to define  
a function that takes all 3 flavors of argument, use const.

The usefulness of invariant for function parameters hasn't really been  
realized yet, but the potential is there (pure functions).

-Steve



More information about the Digitalmars-d mailing list