Optimisation possibilities: current, future and enhancements

Patrick Schluter via Digitalmars-d digitalmars-d at puremagic.com
Fri Aug 26 13:09:16 PDT 2016


On Friday, 26 August 2016 at 19:58:47 UTC, ag0aep6g wrote:
> On 08/26/2016 09:51 PM, Patrick Schluter wrote:
>> On Friday, 26 August 2016 at 14:03:13 UTC, Meta wrote:
> [...]
>>> class Test
>>> {
>>>     int n;
>>>
>>>     void setN(int val) pure
>>>     {
>>>         n = val;
>>>     }
>>>
>>>     int getN() const pure
>>>     {
>>>         return n;
>>>     }
>>> }
>>
>> getN() is not pure, simple as that (and an ideal compiler 
>> should
>> complain in that case). A function is pure if it depends only 
>> of the
>> state passed as parameter. If it touches memory that is set 
>> outside its
>> scope it is NOT PURE!!!
>
> You can rewrite that code like this:
>
> ----
> class Test {/* ... as before but without getN ... */}
> int getN(const Test test) pure { return test.n; }
> ----
>
> Is getN pure now? It only touches memory via the parameter.
>
> For methods we can think of `this` as a hidden parameter. If 
> the method is tagged `const` or `immutable`, it's really that 
> hidden parameter that is being qualified.

Yes. The optimisation of removing the second call is only 
possible if there is no access using the this pointer. The call 
to setN() (or any member function using the mutable this 
pointer), will mandate the compiler to call getN() again.




More information about the Digitalmars-d mailing list