const and immutable objects
Graham St Jack
Graham.StJack at internode.on.net
Tue Sep 1 18:29:22 PDT 2009
On Mon, 31 Aug 2009 15:20:21 -0500, Andrei Alexandrescu wrote:
> Graham St Jack wrote:
>> I have been trying (again) to start using const and immutable objects
>> in a project, and found I kept getting stuck with the need to change
>> the value of object references, which isn't allowed. I don't quite
>> follow the arguments that mean that this has to be the case, but I'm
>> prepared to accept them.
>>
>> After some experimenting with Andrei's Rebindable template, I still
>> couldn't get past the problems. For a start, the get method is private
>> so I couldn't test for null.
>>
>> In the end I cooked up the following, which is a very simple workaround
>> that just lets me assign to a const or immutable object reference. It
>> works just fine, and can be used in templates like containers without
>> forcing the container to care about what it is containing.
>>
>> Comments?
>>
> [snip code]
>
> Hi Graham,
>
> Could you please post a short snippet (or a few) that illustrate the
> problems you ran into with Rebindable?
>
>
> Thanks,
>
> Andrei
The code fragments are lost in the sands of time - I can recreate them if
necessary, but here is an outline of what the problems were:
Rebindable!(Foo) foo = null;
foo = cast(immutable) new Foo(); // ok so far
foo = Foo.init; // still ok
if (foo !is null) {} // compiler error
if (foo.get !is null) {} // another compiler error, and nasty!
The main thing that has to change in Rebindable is that it needs to be a
transparent wrapper, so that "if (foo !is null) {}" works.
What I was doing to get into trouble was writing some communications code
using Fibers, and I wanted the message objects to be immutable (call me
silly, but I wanted to give it a go). This meant I needed to:
* Have a templated queue class that could contain any sort of mutable
types, and const or immutable objects. In particular, I didn't want the
queue to have to use different code for objects and (say) integers.
* Pass messages between the Fibre's stack frame and the main thread, so
for an immutable object reference I needed to: test for null, assign to
null and assign to a new message.
The motivation for passing immutable messages around is that there is an
implicit assumption that these messages don't mutate as they fan out to
various destinations, and I wanted some compiler enforcement.
More information about the Digitalmars-d
mailing list