Meaning of const

H. S. Teoh hsteoh at quickfur.ath.cx
Tue Jan 24 16:55:16 PST 2012


On Tue, Jan 24, 2012 at 07:06:47PM -0500, Jonathan M Davis wrote:
[...]
> So, while a C++ programmer expects that
> 
> int f2() const
> 
> means that f2 is const, they're likely to be surprised by the fact that in
> 
> const int f1()
> 
> it's the int that's const, not f1.
[...]

Wait, I thought 'const int f1()' means that 'int f1(const this, ...)',
not the other way round?

I guess you're trying to say that in C++:

	const int f();

means the return value is 'const int', but in D:

	const int f();

means the same thing as 'int f() const', and the return value is 'int'.
Is that correct?

//

Anyway, I find this variable syntax a bit annoying. The basic syntax of
a function is:

	<return type> <func_name>(<args...>) { <body> }

But now we have additional modifiers like 'pure', 'lazy', 'const', etc.,
and syntax becomes:

	<modifiers> <return type> <func_name>(<args...>) <more_modifiers> { <body> }

Which makes sense, since then you can write 'pure int f()' which reads
nicely. However, in the case of const, it's very confusing because
you're used to writing 'const <typename>' to mean 'const(<typename>)',
yet here 'const int f()' means 'const(int f())' rather than 'const(int)
f()':

	class A {
		const int f();
	}
	auto a = new A;
	const int x;	// typeof(x) == const(int)
	auto y = a.f();	// typeof(y) == int

This is a visual ambiguity with the basic pattern '<return type>
<func_name>(...)', which I find very jarring.

Should I file an issue for this? :)


T

-- 
I think Debian's doing something wrong, `apt-get install pesticide',
doesn't seem to remove the bugs on my system! -- Mike Dresser


More information about the Digitalmars-d-learn mailing list