On 03/19/2010 10:20 PM, Steven Schveighoffer wrote:
What about returning refs that are ref returns or part of other refs?
For example:

ref int foo(ref int x)
{
return x;
}

ref int bar()
{
int x;
return foo(x);
}

The reason I bring this up is because it's exactly what a struct is
doing. Basically, the problem is not so much that you cannot squirrel it
away, but you can return it out of the stack scope it was allocated on.
I don't know if there's a way to fix this without restricting struct
members from returning ref items.

I remember you brought up a similar point in a related discussion a couple of years ago. It's a good point, and my current understanding of the matter is that functions that take and return ref could and should be handled conservatively.

For instance, try to find a rule that prevents the above from compiling,
but allows the following to compile.

struct S
{
private int x;
ref int getX() { return x;}
}

struct T
{
S s;
ref int getSX() { return s.x; }
}

In the approach discussed with Walter, S is illegal. A struct can't define a method to return a reference to a direct member. This is exactly the advice given in Scott's book for C++. (A class can because classes sit on the heap.)

Andrei

Reply via email to