Clarifying 'const' terminology

BCS BCS at pathlink.com
Mon Jul 10 09:21:41 PDT 2006


Bruno Medeiros wrote:
> Derek Parnell wrote:
> 
>> On Sun, 09 Jul 2006 06:05:11 +1000, Kirk McDonald 
>> <kirklin.mcdonald at gmail.com> wrote:
>>
>>
>>
>>> There's another place you can put 'const' in C++:
>>>
>>> class A {
>>>      void bar(int i);
>>>      int foo() const;
>>> };
>>>
>>> This "const" ensures that the member function A::foo does not modify 
>>> the instance of A that you are calling it on. (If the function does 
>>> do so, it is a compile error.) This is an issue when you are dealing 
>>> with const instances of A:
>>>
>>> const A a;
>>>
>>> a.bar(12); // ERROR! a is const, A::bar is not
>>> a.foo();   // Okay
>>>
>>> I actually view this as necessary if we get a way to declare an 
>>> instance as immutable in D. (Honestly, I have few issues with C++ 
>>> const, though this "const-by-default for class instances" idea has 
>>> merit, too.)
>>
>>
>> I can see why this would be a good thing in C++, because the 
>> declaration of A::foo() and the definition of A::foo() is not 
>> necessarily in the same source file or even written by the same 
>> person. This style of 'const' is a way to document a design decision 
>> in source code and thus have the compiler enforce the design.
>>
>> However, in D they are one and the same thing - a class member must be 
>> declared and defined at the same time. So if the design decision is 
>> that A.foo() is not allowed to change any of the data members in an A 
>> object, there is no way to get the compiler to know about that design 
>> decision. So maybe it would be a useful debugging aid.
>>
>> --Derek Parnell
>> Melbourne, Australia
> 
> 
> "However, in D they are one and the same thing - a class member must be 
> declared and defined at the same time."
> Not entirely correct, remember d header files? What happens in D, is 
> that if there is a definition, then there must also be declaration 
> (they're the same actually). But there can be just a definition:
> 
>   class Foo {
>     void func();
>   }
> 
> This means that in D, just as C++, there is no way for the compiler to 
> know in all cases whether the func changes or not the object instance. 
> Thus, it is necessary for the user to specify it.
> 

Another reason that the compiler can't tell is derived classes.

Additionally, letting the compiler check for const methods would 
requirer the checking algorithm to be specified by D. Some algorithms 
will say "go" in the example class is const, some will say it isn't.

class foo
{
	char[] format;

	this(char[] f){ format = f.dup; }	

	char[] go(int i)
	{
		int j;
		char[] f = format;	// f points to member data

		foreach(int k, char c; f)
			if("%" = c)
			{
				j = k;
				break;
			}

		if("%" == f[j])
		{
					// copy f (might not be noticed)
			f = f[0..j+1]~toString(i)~f[j+1..$];

			f[j] = "@";	// assign to f
		}

		return f;
	}
}



More information about the Digitalmars-d-learn mailing list