[Issue 3555] Const function modifies a field when passed a delegate

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Dec 12 10:58:22 PST 2010


http://d.puremagic.com/issues/show_bug.cgi?id=3555


Jonathan M Davis <jmdavisProg at gmx.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |jmdavisProg at gmx.com


--- Comment #1 from Jonathan M Davis <jmdavisProg at gmx.com> 2010-12-12 10:56:37 PST ---
This is not a bug. And the reason is simple: all marking a function as const
does is make its this reference const. So, funkcja becomes something like

void funkcja(const A this, void delegate(int) dg)
{
    dg(3);
}


The delegate has a separate reference to the object that this points to. Even
if you have a pointer or reference to const, it's perfectly legal to alter what
they refer to through another pointer or reference - const just protects what
is const. If you want to _guarantee_ that a const function cannot in any way
alter any aspect of the class or struct that its a part if, that function must
be both const and strongly pure. So, it'll have to be marked const and pure,
and all of its parameters must either be immutable or implicitly castable to
immutable (so, they must either be primitive types or they must be structs that
don't hold non-immutable pointers or references). Otherwise, it's conceivable
that you'll alter the value of the object that this points to through some
indirection. In most cases, you obviously won't but it _is_ possible.

If the object referred to by this were immutable, then that wouldn't be a
problem, because then _no_ pointer or reference could alter it, but as long as
the item referred to be const is actually mutable, then other pointers or
references which aren't pointers or references to const can alter that item.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list