Actually, there are two reasons.

First, it's due to the compilation model of D. Without the signature to convey the information, the compiler cannot make any guarantees. It is legal to declare simply a function signature without the relevant source, in order to link against the function. This means, the compiler does not have access to the source, so if it doesn't have access to the source, how does it know that the function is const or not?

You can solve this at linking, but i have no idea about linking process, it would probably add overhead (data).

Second, it has to do with the desires of the developer who's writing the function.

Let's say you have your code, and the opEquals is treated as const due to the implicit detection of the compiler. Now, you realize your code that compares B types is really slow, so you want to do some sort of caching of the data:

struct A
{
    private B whatever; // changed to private for illustration purposes
    private md5 previousCompare;
    private bool previousCompareResult;

    bool opEquals(A a)
    {
       md5 ah = getMd5sum(a);
       if(ah != previousCompare)
       {
          previousCompare = ah;
          previousCompareResult = (whatever == a.whatever);
       }
       return previousCompareResult;
    }
...
}

So what does the compiler do? Well, not only would this function now silently not be const, it silently un-consts all functions that call it.

You changed the function and the new function is not working, just what you expect. It is not silently is it? Unlike you use "A a" instead of "const A a". this const alone would give you all the guaranties you need.

The point is, many times, people want the compiler to tell them "hey, wait a minute, you marked this as const, but you're trying to do non-const things!" As it turns out, it's really useful to know "this function is not going to change your object/struct." logically, you can make a lot of assumptions based on that. If the compiler doesn't help you enforce that, then stuff like the above creeps into the code, and your const expectation is broken.

I understand the importance of the signatures, but i am trying to understand if this is also practical. What i am saying is, indeed there are many expectations but one thing (not necessarily the solution) is that unless you use "const A a" having const signatures/guaranties pointless, right?

Reply via email to