Sugestion for a const implementation

Andrei Alexandrescu (See Website For Email) SeeWebsiteForEmail at erdani.org
Tue Jan 23 22:54:29 PST 2007


Miles wrote:
> Walter Bright wrote:
[snip]
>> 2) it confuses a type modifier with a storage class (exhibiting muddled
>> special case behaviors)
> 
> Does it? I think this is an implementation issue.

Wrong. It is a definitional issue that confuses even experts.

> I think that in a good const implementation (not exactly compatible with
> C++) the const variant of a type should be the same as the non-const
> variant, just with a special "property" that restricts access, and not a
> completely different type.
> 
> This means that
> 
> 	class X {
> 		X func(Y a);
> 		const X func(const Y a) const;
> 	};
> 
> would generate a compile-time error, since both member functions are
> identical once you make const a reference property, and not a different
> type.

That's pretty limiting; you can't define something a la STL begin() that 
returns different objects depending on the object's mutability.

>> 3) it's ugly and litters declarations
> 
> Sorry, but it is your personal opinion. This doesn't make const bad.

Littering declarations is objective. In C++ const is never deduced, only 
checked. The underlying vision is that there should be cases in which 
constness is deduced such that programmers can benefit of it without 
having to babysit the compiler.

>> 4) the use of overloading based on const is a workaround to another
>> design flaw in C++
> 
> If you mean like the above case, yeah, sure. This does not mean that
> this problem have no solution. I foresee a very simple solution like the
> covariant return type already implemented in D. It is not that difficult.
> 
> There are three cases for returning const types:
>   (1) the member function should always return a const reference,
>   (2) the member function should always return a non-const reference
> (like a copy operator), and
>   (3) the member function should return a self-reference, respecting the
> const-ness of the object reference it was called from.

Sorry, this is simplistic and incomplete. A member function might want 
to return whatever, including two unrelated types depending on constness.


Andrei



More information about the Digitalmars-d mailing list