Const transitivity is bad sometimes
naryl
cy at ngs.ru
Tue Jan 15 20:02:33 PST 2008
On Mon, 14 Jan 2008 17:01:27 +0300, Jason House
<jason.james.house at gmail.com> wrote:
> naryl wrote:
>
>> For example, I have this piece of (useless) code:
>>
>> http://paste.dprogramming.com/dpmmwnah
>>
>> If there were more subscribers the same message would be sent to every
>> one
>> of them. And there may be several messages, carrying the same notifier
>> as
>> their data. While compiling this I got the following errors (DMD 2.009):
>>
>> main.d(28): function main.SystemShutdownNotifier.addSubscriber
>> (Subscriber) does not match parameter types (Subscriber)
>> main.d(28): Error: (cmd.notifier).addSubscriber can only be called on a
>> mutable object, not const(SystemShutdownNotifier)
>>
>> I know. Notifier has become const because const is transitive, but in
>> this
>> example I don't need transitivity. I can't even think of a workaround
>> for
>> that. Maybe someone can help?
>
> I think this is the classic sort of problem people have complained about
> with const transitivity. I don't know what people have suggested as the
> workaround for this. Personally, I've been thinking it'd be nice to mark
> objects with something that says "I'll write to this, but will never read
> from it".
I've found several similar cases. It happens when short-lived invariant
object has reference to long-lived mutable object, but not the object
itself. When one object creates, contains and finalizes another it is
logical to make contained object invariant if container is invariant. But
when (as in example) invariant Message is used only to deliver notifier to
several subscribers, transitive const doesn't fit. Of course I can cast it
away, but on http://www.digitalmars.com/d/const3.html it states that
"modification after casting away const" [is] "undefined behavior".
More information about the Digitalmars-d-learn
mailing list