Const sucks
Nathan Reed
nathaniel.reed at gmail.com
Mon Sep 10 21:29:08 PDT 2007
Walter Bright wrote:
> Bruno Medeiros wrote:
>> Walter Bright wrote:
>>> What, exactly, is the use case that needs a solution?
>>
>> Before hand, let me just say that by broken, I didn't mean
>> subvertable, but rather that using const/invariant with classes would
>> be impractical and unmanageable.
>>
>> Simple example: Let's say you have a class Foo that is comparable. How
>> do you sort an array of const(Foo)'s ?
>>
>> const(Foo)[] sort(const(Foo)[] arr) {
>> ... ?
>> The sorting algorithm doesn't matter, what matters is: how would one
>> swap two elements in the array?
>
> You can't sort an (array of)(const T). You can sort an (array
> of)(something of)(const T).
I may be misunderstanding this. When you declare an array const(C)[]
where C is a class type, it's really an array of *references* to objects
(of class C), right? So it seems unreasonable to restrict such an array
from being sorted, since you can sort the references without modifying
the objects' contents.
In general, I'd think there would be lots of situations where you want
to be able to hold a reference to an object, through which you don't
want to allow the object's contents to be changed, but you *do* want to
be able to change the reference to refer to different objects at
different times. In other words, tail-const.
(One concrete example comes from interactive graphics. Say we have some
set of objects that represent pieces of geometry to be drawn. The
rendering routine shouldn't modify the geometry, so the objects'
contents should be const. But it should sort the geometry for the most
efficient rendering order, so it needs to be able to have a non-const
array of references to constant objects.)
Thanks,
Nathan Reed
More information about the Digitalmars-d
mailing list