Persistent list
Timon Gehr via Digitalmars-d
digitalmars-d at puremagic.com
Sun Nov 15 18:38:37 PST 2015
On 11/16/2015 03:25 AM, Andrei Alexandrescu wrote:
>> In one particular case.
>>
>> import package.module : foo, bar, baz, fun;
>>
>> final class C{
>> int x;
>> private this(int x){ this.x=x; }
>> }
>>
>> void main(){
>> auto c = new C(2);
>> foo(c); // void foo(const C c);
>> bar(); // impure
>> baz(); // impure
>> fun(c.x); // this read of c.x can be optimized away under current
>> semantics, not under the new ones
>> }
>
> Actually, you're wrong here. Typechecking main() does not take C's
> constructor's body into consideration, just the signature. So all the
> compiler knows about C whilst typechecking main() is:
>
> final class C {
> int x;
> private this(int x);
> }
>
> What could happen (implausibly, but typechecking must be conservative)
(Optimizations are not the same as type checking.)
> is that C's constructor may communicate with foo's package through a
> global, e.g. setting a global int* with the address of x. Then clearly
> the read of c.x cannot be optimized away today.
>
D's unit of encapsulation is the module, so the compiler actually knows
the body of the constructor of C while optimizing main.
> It's possible a class of examples can be found, but this is not one.
One could just use a struct and inline the constructor, if you think
that helps. Another way to avoid your objection is to make the
constructor pure.
More information about the Digitalmars-d
mailing list