Lambda access to stackalloc variables #2182
Replies: 4 comments
-
And now I'm starting to doubt myself because it is, after all, unsafe code. You told the compiler to trust you, the fact that you betrayed that trust isn't going to always be discoverable. |
Beta Was this translation helpful? Give feedback.
-
I guess the issue with that is that unsafe code is explicitly that - unsafe. Someone who has opted into unsafe code is meant to know about the risks, and deal with them. He doesn't want to be given warnings about dangerous code. If course it's dangerous! That's why it's unsafe! Adding a warning to code that already existed and works fine will just annoy them. |
Beta Was this translation helpful? Give feedback.
-
I wish there was a chaos keyword too. |
Beta Was this translation helpful? Give feedback.
-
@Damien-The-Unbeliever using System;
using System.Threading;
class Program
{
static void Main(string[] args)
{
for (int i = 0; i < 5; i++)
call(i);
Thread.Sleep(1000);
}
static void call(int number) //this is no longer 'unsafe'
{
Span<int> ints = stackalloc int[64];
ints[32] = number;
ThreadPool.QueueUserWorkItem(delegate { execute(ints[32]); }); //<-- error CS8175
}
static void execute(int number)
{
Console.WriteLine(" * NUM=" + number.ToString());
}
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Someone has posed a question on Stackoverflow asking why a
stackalloc
variable isn't correctly captured by a lambda.The more I think about this, the more I think that just writing such a thing should produce a warning - lambdas have an uncertain lifetime that may live longer than the stack frame in which they're created, but
stackalloc
is an explicit statement that the lifetime of an object should only last as long as the current stack frame. There doesn't seem to be a natural way for these two features to interact safely.But as currently implemented, no error or warning is produced by this code:
(Copied from question)
Should at least a new warning be produced for such code? (Because it may be known by the author that the useful life of the lambda doesn't extend beyond the lifetime of the stackframe, I'm thinking an error wouldn't be appropriate)
Beta Was this translation helpful? Give feedback.
All reactions