Bug 3555 – Const function modifies a field when passed a delegate

Status
RESOLVED
Resolution
INVALID
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
x86
OS
Windows
Creation time
2009-11-28T04:43:00Z
Last change time
2015-06-09T01:27:04Z
Assigned to
nobody
Creator
tomeksowi

Comments

Comment #0 by tomeksowi — 2009-11-28T04:43:30Z
I believe this should not compile: class A { public: int pole; void funkcja(void delegate(int) dg) const { dg(3); } } void main() { A a = new A; void zmien(int w) { a.pole = w; } a.funkcja(&zmien); // pole changed by calling const funkcja assert (a.pole == 3); } Looks very similar to bug 3534.
Comment #1 by issues.dlang — 2010-12-12T10:56:37Z
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.
Comment #2 by bugzilla — 2010-12-12T13:30:27Z
Jonathan's remarks are correct. Not a bug.