Bug 9597 – using "this" as a type leads to confusion
Status
RESOLVED
Resolution
DUPLICATE
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-02-26T11:23:52Z
Last change time
2018-05-12T13:22:11Z
Assigned to
No Owner
Creator
Ivan Kazmenko
Comments
Comment #0 by gassa — 2013-02-26T11:23:52Z
Using "this" as a type in method parameter declarations is not universal because of the postblit constructor signature. It also creates confusion when the method signature resembles the postblit constructor.
Here are a few examples of what can and cannot be declared (DMD 2.062):
-----
struct S
{
int x = 1;
int y = 0;
this (this) // postblit constructor called like this: "S b = a;"
{
x = 10;
y = 1;
}
this (ref this) // constructor called as: "S c = S (a);"
{
x = 100;
}
this (S q) // compiles, example call: "S d = S (S (a));"
{
x = 1000;
}
this (ref this, this t) // compiles, called as: "S e = S (a, b);"
{
x = 10_000;
}
/*
this (this r) // does not compile: found 'r' when expecting ')'
{ // would be equivalent to: "this (S r)"
x = 100_000;
}
this (this, this s) // does not compile: found ',' when expecting ')'
{ // would be equivalent to: "this (S, S s)"
x = 1_000_000;
}
*/
}
import std.stdio;
void main ()
{
S a;
S b = a;
S c = S (a);
S d = S (S (a));
S e = S (a, b);
writeln (a.x, " ", a.y); // 1 0
writeln (b.x, " ", b.y); // 10 1
writeln (c.x, " ", c.y); // 100 0
writeln (d.x, " ", d.y); // 1000 0
writeln (e.x, " ", e.y); // 10000 0
}
-----
Now, "this(this)" is the postblit constructor and thus an understandable exclusion. Still, the reason "this(this r)" or "this(this, this s)" do not currently compile - while other examples compile and run smoothly - seems arbitrary and technical.
To always require using "typeof(this)" instead of "this" for the type would be less confusing.
An intermediate yet not-so-confusing solution would be to forbid using "this" in constructor parameter declarations while still permitting it in other method declarations.
Hmm, this is caused by issue 2540. Makes me think 2540 was a mistake, as `alias x = this.foo;` is technically aliasing an expression.
CCing Kenji because he was involved in the discussion.
Comment #3 by andrej.mitrovich — 2014-05-02T14:23:57Z
Although this was the earlier bug, I'm marking this as a duplicate: Issue 18228 covers `this` in a parameter list and is now fixed. Issue 12228 is still outstanding.
*** This issue has been marked as a duplicate of issue 18228 ***