On Friday, 26 August 2016 at 20:35:13 UTC, ag0aep6g wrote:
On 08/26/2016 10:09 PM, Patrick Schluter wrote:
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.
If setN is called or not does not affect getN's purity, though.
You wrote that (the method) getN is not pure and should be
rejected by the compiler, but both variants (method and
function) are equally pure or impure.
Yeah, I was wrong, the function getN() is pure (but not const).
The thing is, that the compiler can remove a second call to a
pure function only if it can make sure that there are no memory
changes via one of the pointers of the functions. To give an
example coming from C (sorry, I'm nearly only a C man).
strlen(p) is pure. A second call to strlen(p) can only by removed
if the compiler can guarantee that no change was done to the
memory pointed to by p. Unfortunately that does not happen really
that often. Even a simple call to strcpy(whatever, p) will break
the optimisation (char * are always potentially aliased).
So again, sorry for posting too quickly, shouldn't post after
drinking Belgian beer ;-)