Logical const

Jesse Phillips jessekphillips+D at gmail.com
Wed Dec 1 09:43:38 PST 2010


Jordi Wrote:

> Is the "const" keyword (both in C++, and in D) for the developer writing 
> code, or for the compiler compiling it?

It is for the compiler to enforce what the developer is saying it is.

>  From what Walter said (and it makes a lot of sense to me), in the case 
> of C++ it is only a hint to the programmer that the compiler will 
> enforce you, but internally the compiler cannot really use it for anything.

But the compiler is does not enforce it. At least people assume it is transitive when it is not.
 
> On the other side, in D, it is a hint to the compiler but it will only 
> use it if is verifiable. If that is the case, why do we need the "const" 
> keyword in the first place? The compiler can already verify that the 
> code is const and do the proper opimizations.

It can, unless the source is not available. Though it could probably output the information when creating .di files.
 
> Steve's solution would be on the side of "useful for the programmer, 
> enforced by the compiler, uselss for the compiler".

But it isn't enforced by the compiler. It can enforce that you only modify things you claimed could be modified. But it can't enforce that it is logically const. It could prevent the modifiable parts from influencing the result, but then the requested caching isn't possible.

> Please let me know if i wrote something that doesn't make sense.
> 
> Jordi

I do not believe you will run into issues with casting in a const function if logical const is truely happening.

The areas that could be an issue is when what you are casting is immutable and placed in read-only memory. In which case you should avoid creating immutable objects that use logical const.

Personally I would like to know how pointers/references in an immutable are dealt with when creating or passing them to a thread/process.

struct Foo {
    int* foo;
}

immutable Foo f;

I believe that if this data is copied, such as in concurrent program, the data referenced by foo may also be placed in read only memory as immutable is defined to never change (though it can due to casting). Is this correct?


More information about the Digitalmars-d mailing list