www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - const violation?

reply "H. S. Teoh" <hsteoh quickfur.ath.cx> writes:
Why does the following code compile?

	import std.stdio;
	int f(ref int x) {
		return x++;
	}
	class A {
		int x=123;
		int g() const {
			return f(x);
		}
	}
	void main() {
		auto a = new A;
		writeln(a.g());
		writeln(a.g());
	}

Shouldn't the const member g() be prohibited from passing a ref to a
member variable to f()?

But this code not only compiles, it outputs:

	123
	124

So I've managed to call a const member of A to alter the value of A.x?
Am I misunderstanding the meaning of const when applied to a member
function, or is this a compiler bug?

P.S. I'm using gdc-4.6; does dmd also have this behaviour?


T

-- 
Lawyer: (n.) An innocence-vending machine, the effectiveness of which
depends on how much money is inserted.
Jan 13 2012
parent "Steven Schveighoffer" <schveiguy yahoo.com> writes:
On Fri, 13 Jan 2012 15:27:56 -0500, H. S. Teoh <hsteoh quickfur.ath.cx>  
wrote:

 Why does the following code compile?

 	import std.stdio;
 	int f(ref int x) {
 		return x++;
 	}
 	class A {
 		int x=123;
 		int g() const {
 			return f(x);
 		}
 	}
 	void main() {
 		auto a = new A;
 		writeln(a.g());
 		writeln(a.g());
 	}

 Shouldn't the const member g() be prohibited from passing a ref to a
 member variable to f()?
Yes, it's a bug (I think already reported, let me check... Yep: http://d.puremagic.com/issues/show_bug.cgi?id=5493)
 But this code not only compiles, it outputs:

 	123
 	124

 So I've managed to call a const member of A to alter the value of A.x?
 Am I misunderstanding the meaning of const when applied to a member
 function, or is this a compiler bug?

 P.S. I'm using gdc-4.6; does dmd also have this behaviour?
Yes, the pull request hasn't been merged yet. BTW, I tested with 2.057, which I downloaded from github. Holy CRAP, downloaded in less than 1 second!!! Awesome :) Can we archive all the old DMD downloads there? -Steve
Jan 13 2012