Ramifications of const

Don Clugston dac at nospam.com.au
Wed Jun 13 06:30:27 PDT 2007


eao197 wrote:
> On Wed, 13 Jun 2007 16:13:01 +0400, Georg Wrede <georg at nospam.org> wrote:
> 
> <...skipped...>
> 
>> Conclusion
>>
>> For the purposes of language development, we now have two attributes 
>> for each function: does it change its arguments, and does it change 
>> anything else. I'd actually like to have these incorporated into the 
>> function signature. A function can only be Pure if all the functions 
>> it calls are Pure (i.e. do not change anything) and it is Pure itself.
> 
> That all is already in C++:
> 
> class Demo {
> public :
>   // Does not change anything in the Demo instance.
>   void f() const;
>   // Changes something in the Demo instance.
>   void f1();
> 
>   // Does not change any argument.
>   // Changes something in the Demo instance.
>   void f2( int a, const char * b, const Something & c );
> 
>   // Does not change any argument.
>   // Does not change anything in the Demo instance.
>   void f3( int a, const char * b, const Something & c ) const;
> 
>   // Changes a, b and c.
>   // Changes something in the Demo instance.
>   void f4( int & a, char * b, Something & c );
>   // Changes a, b and c.
>   // Does not change anything in the Demo instance.
>   void f5( int & a, char * b, Something & c ) const;
> };
> 
> Yes, there are possible changes to some global variables or to mutable 
> members of Demo.

It's worse than that. You can call any global function, or any static function 
of any class.  eg, deleteAllFilesOnHardDisk();
Moreover, you can const_cast<> and change anything at all. C++ const gives you 
no guarantees whatsoever.

>> It might be useful to have "does chanege its arguments" as a flag 
>> which can quickly be checked during compilation, even if it is 
>> deducable from the argument declarations. This may speed things up. 
>> But the *more* important flag would be whether the function may change 
>> "external" things. This is hard to see without a flag in the signature.
> 
> I think if someone want to have 'pure functions' then it is better to 
> look to functional programming languages.

And it's one of the good ideas from functional programming languages.
Note that any pure function is a candidate for CTFE (if called with constant 
arguments), so it's becoming useful for D.



More information about the Digitalmars-d mailing list