Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed/moveable variables versus locals captured in a lambda #2496

Open
gafter opened this issue Sep 22, 2016 · 0 comments
Open

Fixed/moveable variables versus locals captured in a lambda #2496

gafter opened this issue Sep 22, 2016 · 0 comments
Assignees

Comments

@gafter
Copy link
Member

gafter commented Sep 22, 2016

The language spec (18.3 Fixed and moveable variables) says

In precise terms, a fixed variable is one of the following:

  • A variable resulting from a simple-name (§7.6.2) that refers to a local variable or a value parameter, unless the variable is captured by an anonymous function.
  • A variable resulting from a member-access (§7.6.4) of the form V.I, where V is a fixed variable of a struct-type.
  • A variable resulting from a pointer-indirection-expression (§18.5.1) of the form *P, a pointer-member-access (§18.5.2) of the form P->I, or a pointer-element-access (§18.5.3) of the form P[E].
    All other variables are classified as moveable variables.

But testing this on the following program

using System;

unsafe struct S
{
    public fixed int buffer[1];
    public int i;
}

unsafe class Test
{
    private void example1()
    {
        S data = new S();
        Func<S> lambda = () => data;
        fixed (int* p = &data.i) // ok; data is captured
        {
        }
        fixed (int* p = data.buffer) // ok; data is captured
        {
        }
    }
}

We find that Roslyn reject both attempts, complaining that you can't take the address of a variable that has been captured by a lambda, AND that you can't use the fixed statement to take the address of an already fixed expression.

Why does the language forbid using a fixed statement for a fixed variable? It would just be a no-op. Allowing it would sidestep having to specify which variables are captured in an async method. We could just say that there are no fixed variables in an async method, and force people to use the fixed statement (which might sometimes be a no-op).

@gafter gafter transferred this issue from dotnet/roslyn May 6, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants