Meaning of const variables

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Tue Jun 21 08:21:01 PDT 2016


On 06/21/2016 06:48 AM, jmh530 wrote:

 > So an immutable pointer guarantees that whatever it is pointing to will
 > never change,

Yes but saying "_requires_ that data never changes" is more correct. 
When it comes to a pointer (i.e. the user of data), "guarantee" is 
related to const.

 > but a const pointer can also point to mutable data, which
 > might change some other way.

Yes, const means "_I_ will not change."

const and immutable are not interesting unless there are references. 
Otherwise, who cares whether data was copied from const or immutable?

     const c = 42;
     immutable i = 43;

     int a = c;
     int b = i;

a and b are copied from const and immutable, respectively, but we don't 
care. (Except when they have members or members of members that are 
references.)

const and immutable are interesting when there are references, of which, 
function parameters make the issue clear to me:

void foo(ref const int c, ref immutable int i) {
     // ...
}

foo says "I guarantee that I will not modify your data, which I'm 
referring to as c" and "I require that nobody will modify your data, 
which I'm referring to as i". So, the const-immutable distinction of a 
reference parameter is what makes it easy to understand to me.

As I observe in that chapter[1] and later in the book[2], it's not 
always clear which one to use. For example, although const seems more 
usable, the fact that it has to work with mutable and immutable 
necessarily "erases" the actual mutability[1].

Another example is with constructor parameters where immutable is 
potentially faster[2]. That chapter does not really explain why so here 
is an example:

struct S {
     string fileName;    // Needs immutable

     // Takes as const reference, presumably to be more useful
     this(const char[] fileName) {
         // Since const does not guarantee immutability, must take a copy
         import std.conv;
         this.fileName = fileName.to!string;
     }
}

void main() {
     // The copy in the constructor is unnecessary in this case because here
     // the string is already immutable. S's constructor could not know 
that so
     // it had to take a copy.
     auto s = S("my_file");
}

The same issue applies for other functions where a reference needs to be 
kept longer for later use.

Ali

[1] 
http://ddili.org/ders/d.en/const_and_immutable.html#ix_const_and_immutable.parameter,%20const%20vs.%20immutable

[2] http://ddili.org/ders/d.en/special_functions.html
(Search for the section "Immutability of constructor parameters".)



More information about the Digitalmars-d-learn mailing list