On Fri, 04 Feb 2011 13:49:42 -0500, so <s...@so.do> wrote:


Now, what i mean with this:

---
struct A {
        B whatever;
        bool opEquals(A a) {
return whatever == a.whatever; // just comparision, this function is const
        }
        bool anything(A a) {
                whatever = 2; // here i have an assignment, this function is 
not const
                return whatever;
        }
}
---

It doesn't matter what signature you use for the function, compiler is aware and will output an error when you do the opposite of the signature. If this is the case, why do we need that signature?
Its presence just makes things complicated and with actually no reason.

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?

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.

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.

What's somewhat unfortunate is that once you mark something as const, you have to mark all sorts of other things as const. So for example, B's opEquals must also be const. However, if you properly mark items as const when they really are const, this should already be the case.

The statement that "you don't need to use const if you don't want to" is really weak. If you use D libraries, you will undoubtedly have to use const (once const is sane and libraries start using it). But using it is not "pointless" and does add value.

-Steve

Reply via email to