D Programming Language
Report a bug If you spot a problem with this page, click here to create a Bugzilla issue. Improve this page Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

# Type Qualifiers

Type qualifiers modify a type by applying a TypeCtor. TypeCtors are: const, immutable, shared, and inout. Each applies transitively to all subtypes.

## Const and Immutable

When examining a data structure or interface, it is very helpful to be able to easily tell which data can be expected to not change, which data might change, and who may change that data. This is done with the aid of the language typing system. Data can be marked as const or immutable, with the default being changeable (or mutable).

immutable applies to data that cannot change. Immutable data values, once constructed, remain the same for the duration of the program's execution. Immutable data can be placed in ROM (Read Only Memory) or in memory pages marked by the hardware as read only. Since immutable data does not change, it enables many opportunities for program optimization, and has applications in functional style programming.

const applies to data that cannot be changed by the const reference to that data. It may, however, be changed by another reference to that same data. Const finds applications in passing data through interfaces that promise not to modify them.

Both immutable and const are transitive, which means that any data reachable through an immutable reference is also immutable, and likewise for const.

## Immutable Storage Class

The simplest immutable declarations use it as a storage class. It can be used to declare manifest constants.

    immutable int x = 3;  // x is set to 3
    x = 4;        // error, x is immutable
    char[x] s;    // s is an array of 3 char's

The type can be inferred from the initializer:

    immutable y = 4; // y is of type int
    y = 5;           // error, y is immutable

If the initializer is not present, the immutable can be initialized from the corresponding constructor:

    immutable int z;
    void test()
    {
        z = 3; // error, z is immutable
    }
    static this()
    {
        z = 3; // ok, can set immutable that doesn't
               // have static initializer
    }

The initializer for a non-local immutable declaration must be evaluatable at compile time:

    int foo(int f) { return f * 3; }
    int i = 5;
    immutable x = 3 * 4;      // ok, 12
    immutable y = i + 1;      // error, cannot evaluate at compile time
    immutable z = foo(2) + 1; // ok, foo(2) can be evaluated at compile time, 7

The initializer for a non-static local immutable declaration is evaluated at run time:

    int foo(int f)
    {
        immutable x = f + 1;  // evaluated at run time
        x = 3;                // error, x is immutable
    }

Because immutable is transitive, data referred to by an immutable is also immutable:

    immutable char[] s = "foo";
    s[0] = 'a';  // error, s refers to immutable data
    s = "bar";   // error, s is immutable

Immutable declarations can appear as lvalues, i.e. they can have their address taken, and occupy storage.

## Const Storage Class

A const declaration is exactly like an immutable declaration, with the following differences:

- Any data referenced by the const declaration cannot be changed from the const declaration, but it might be changed by other references to the same data.
- The type of a const declaration is itself const.

## Immutable Type

Data that will never change its value can be typed as immutable. The immutable keyword can be used as a type qualifier:

    immutable(char)[] s = "hello";

The immutable applies to the type within the following parentheses. So, while s can be assigned new values, the contents of s[] cannot be:

    s[0] = 'b';  // error, s[] is immutable
    s = null;    // ok, s itself is not immutable

Immutability is transitive, meaning it applies to anything that can be referenced from the immutable type:

    immutable(char*)** p = ...;
    p = ...;        // ok, p is not immutable
    *p = ...;       // ok, *p is not immutable
    **p = ...;      // error, **p is immutable
    ***p = ...;     // error, ***p is immutable

Immutable used as a storage class is equivalent to using immutable as a type qualifier for the entire type of a declaration:

    immutable int x = 3;   // x is typed as immutable(int)
    immutable(int) y = 3;  // y is immutable

## Creating Immutable Data

The first way is to use a literal that is already immutable, such as string literals. String literals are always immutable.

    auto s = "hello";   // s is immutable(char)[5]
    char[] p = "world"; // error, cannot implicitly convert immutable
                        // to mutable

The second way is to cast data to immutable. When doing so, it is up to the programmer to ensure that no other mutable references to the same data exist.

    char[] s = ...;
    immutable(char)[] p = cast(immutable)s;     // undefined behavior
    immutable(char)[] p = cast(immutable)s.dup; // ok, unique reference

The .idup property is a convenient way to create an immutable copy of an array:

    auto p = s.idup;
    p[0] = ...;	  // error, p[] is immutable

## Removing Immutable or Const with a Cast

An immutable or const type qualifier can be removed with a cast:

    immutable int* p = ...;
    int* q = cast(int*)p;

This does not mean, however, that one can change the data:

    *q = 3; // allowed by compiler, but result is undefined behavior

The ability to cast away immutable-correctness is necessary in some cases where the static typing is incorrect and not fixable, such as when referencing code in a library one cannot change. Casting is, as always, a blunt and effective instrument, and when using it to cast away immutable-correctness, one must assume the responsibility to ensure the immutability of the data, as the compiler will no longer be able to statically do so.

Note that casting away a const qualifier and then mutating is undefined behavior, too, even when the referenced data is mutable. This is so that compilers and programmers can make assumptions based on const alone. For example, here it may be assumed that f does not alter x:

    void f(const int* a);
    void main()
    {
        int x = 1;
        f(&x);
        assert(x == 1); // guaranteed to hold
    }

## Immutable Member Functions

Immutable member functions are guaranteed that the object and anything referred to by the this reference is immutable. They are declared as:

    struct S
    {
        int x;

        void foo() immutable
        {
            x = 4;      // error, x is immutable
            this.x = 4; // error, x is immutable
        }
    }

Note that using immutable on the left hand side of a method does not apply to the return type:

    struct S
    {
        immutable int[] bar()  // bar is still immutable, return type is not!
        {
        }
    }

To make the return type immutable, you need to surround the return type with parentheses:

    struct S
    {
        immutable(int[]) bar()  // bar is now mutable, return type is immutable.
        {
        }
    }

To make both the return type and the method immutable, you can write:

    struct S
    {
        immutable(int[]) bar() immutable
        {
        }
    }

## Const Type

Const types are like immutable types, except that const forms a read-only view of data. Other aliases to that same data may change it at any time.

## Const Member Functions

Const member functions are functions that are not allowed to change any part of the object through the member function's this reference.

## Implicit Conversions

Values can be implicitly converted between mutable, const, immutable, shared const, inout and inout shared.

References can be converted according to the following rules:

Implicit Conversion of Reference Types
from/to | mutable | const | shared | shared const | inout | inout const | inout shared | inout shared const | immutable
,
mutable | ✔ | ✔ |  |  |  |  |  |  |
const |  | ✔ |  |  |  |  |  |  |
shared |  |  | ✔ | ✔ |  |  |  |  |
shared const |  |  |  | ✔ |  |  |  |  |
inout |  | ✔ |  |  | ✔ | ✔ |  |  |
inout const |  | ✔ |  |  |  | ✔ |  |  |
inout shared |  |  |  | ✔ |  |  | ✔ | ✔ |
inout shared const |  |  |  | ✔ |  |  |  | ✔ |
immutable |  | ✔ |  | ✔ |  | ✔ |  | ✔ | ✔

If an implicit conversion is disallowed by the table, an Expression may be converted if:

An expression may be converted from mutable or shared to immutable if the expression is unique and all expressions it transitively refers to are either unique or immutable.

An expression may be converted from mutable to shared if the expression is unique and all expressions it transitively refers to are either unique, immutable, or shared.

An expression may be converted from immutable to mutable if the expression is unique.

An expression may be converted from shared to mutable if the expression is unique.

A Unique Expression is one for which there are no other references to the value of the expression and all expressions it transitively refers to are either also unique or are immutable. For example:

    void main()
    {
        immutable int** p = new int*(null); // ok, unique

        int x;
        immutable int** q = new int*(&x); // error, there may be other references to x

        immutable int y;
        immutable int** r = new immutable(int)*(&y); // ok, y is immutable
    }

Otherwise, a CastExpression can be used to force a conversion when an implicit version is disallowed, but this cannot be done in @safe code, and the correctness of it must be verified by the user.

Copyright © 1999-2015 by Digital Mars ®, All Rights Reserved | Page generated by Ddoc on Wed Nov 11 10:37:55 2015