On 01-09-2011 21:26, Timon Gehr wrote:
On 09/01/2011 09:18 PM, Alex Rønne Petersen wrote:
On 01-09-2011 21:13, Steven Schveighoffer wrote:
On Thu, 01 Sep 2011 15:08:29 -0400, Alex Rønne Petersen
<[email protected]> wrote:

Hi,

Consider this:

struct S
{
static S opAssign(int rhs)
{
return S();
}
}

void main()
{
S s;
s = 1;
}

And:

struct S
{
S opAssign(int rhs)
{
return S();
}
}

void main()
{
S s;
s = 1;
}

Both will compile. I don't get it. I can understand it in the case of
the static opAssign, but with the non-static one, what does 'this'
refer to inside opAssign? And why are both seemingly allowed?

s = 1 is rewritten as s.opAssign(1). So in the non-static version,
'this' refers to the struct you called the function with (in your
example, s).

so:

struct S
{
int x;
S opAssign(int rhs)
{
x = rhs;
return this;
}
}

void main()
{
S s;
s = 5;
assert(s.x == 5);
}

Since you are allowed to call static member functions, s.opAssign(1) for
the static one succeeds, but some of us are pushing to make this
invalid. It makes things very confusing when you call static functions,
but it looks like you are calling non-static member functions.

-Steve

So that's to say x = 5; with a static opAssign would actually just... do
nothing?

- Alex

It will execute the body of static opAssign which could contain
arbitrary code.




Oh right. Hadn't thought of that. It still seems very obscure, though.

- Alex

Reply via email to