Constant relationships between non-constant objects

Sebastian Unger via Digitalmars-d digitalmars-d at puremagic.com
Tue Jun 17 19:28:19 PDT 2014


On Wednesday, 18 June 2014 at 02:00:37 UTC, Justin Whear wrote:
> On Wed, 18 Jun 2014 01:31:32 +0000, Sebastian Unger wrote:
>
>> Hi there,
>> 
>> I'm an experient C++ developer and am trying to switch to / 
>> learn D.
>> What I've seen so far is mostly quite straight forward and 
>> VERY nice.
>> 
>> There's only one catch so far for me for which Googling has 
>> only found
>> the discouraging answer of: It can't be done in D.
>> 
>> I have two classes A and B. Each object of class A is 
>> associated with a
>> particular object of class B. This association is not supposed 
>> to change
>> throughout the lifetime of the object of A.
>> 
>> How am I supposed to express this in D, given that D's const 
>> is too
>> strong for this? I don't need any guarantees from the const 
>> that can be
>> used for thread safety or parallelisation. All I need is the 
>> compiler
>> not letting me change the reference to the B object inside the 
>> A object.
>> 
>> Does D have some way of expressing this?
>> 
>> Or has D really done away with the MOST important use case of 
>> const
>> (preventing developer mistakes! Not optimization.)
>> 
>> Cheers,
>> Seb
>
> I think you may be mixing up const and immutable.  What do you 
> mean about
> const being too strong?
>
> It seems that does what you want:
>
> class A
> {
>     const B bff;
>
>     this(B bestBuddy)
>     {
>         bff = bestBuddy;
>     }
> }

You missed the point about A needing to modify B. I want to 
express a constant relationship between objects, not that A or B 
are constant.

Cheers,
Seb


More information about the Digitalmars-d mailing list