pure or not pure?

Georg Wrede georg at nospam.org
Thu Apr 10 14:01:28 PDT 2008


Steven Schveighoffer wrote:
> "Georg Wrede" wrote
> 
>>Ehrm. On second thought, it actually IS possible to end up in a situation 
>>where a just newed object may suddenly change in your hands, and also be 
>>referenced from other parts of the program.
>>
>>(I'll leave constructing an example as an exercise.)
>>
>>Now, the simplest thing to guarantee that not happening would be to deny 
>>newing of objects that have constructors.
> 
> 
> In fact, I think the solution to this is to make a constructor that is pure 
> :)

Yes. And thus, a pure constructor cannot write to class variables, only 
instance variables.

> The problem with this is that the 'this' pointer is mutable when passed to 
> the constructor, so you have mutable data being passed to a pure function. 
> However, it is 'unique' data that has not been initialized anywhere, so this 
> might be an exception to the rule.

I agree. One might consider the "this" varable as either actually 
pointing to this particular instance or else consider it invalid. If we 
define it so, then "this" can be considered immutable.

Besides, since we don't have a reallocating GC, and we can't (at least I 
don't now remember otherwise) store object instances in (potentially 
relocating) arrays (only references to them), the "this" pointer could 
be made immutable everywhere.

> Having the constructor pure solves any problems because you can't pass the 
> 'this' pointer out to some global function that might store it somewhere.

Yes.



More information about the Digitalmars-d mailing list