On Fri, 04 Feb 2011 15:26:07 -0500, so <s...@so.do> wrote:

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).

Yes, but that requires a custom linker/object file format. Java does this, and D could do it, but it requires a major investment of time/effort.

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.

It is silent. This is a basic difference in philosophy. What it boils down to is declaration vs. usage.

Let's say I *don't* use const A a anywhere, so my code just compiles, I then release my library, and your code breaks because you do use const A a. You might just be screwed, because I say "I don't care, I never meant that function to be const". Now, you are stuck on an older version of the library, or forced to make drastic changes to your code.

Conversely, if the compiler *requires* the const decoration in the signature, your code never compiles to begin with, you can either work around the limitation, file a bug, or use a different library. But since the API isn't going to change, you can be sure future versions of my code will work.

I feel the second scenario is better for all -- declare what you intend for the API, then there are no surprises later.

-Steve

Reply via email to