Type inference and overloaded functions

Jonathan M Davis jmdavisProg at gmx.com
Thu Dec 12 22:50:27 PST 2013


On Friday, December 13, 2013 07:19:50 Maxim Fomin wrote:
> On Friday, 13 December 2013 at 04:13:04 UTC, Kenji Hara wrote:
> > On Thursday, 12 December 2013 at 18:20:25 UTC, bearophile wrote:
> >> If I have a function foo that takes a slice as input, and I
> >> want to pass it two arrays, the first time allocated on the
> >> heap and the second on the stack, I have to use an auxiliary
> >> variable:
> >> 
> >> 
> >> void foo(int[]) {}
> >> void main() {
> >> 
> >>    foo([1, 2, 3]);
> >>    int[3] tmp = [4, 5, 6];
> >>    foo(tmp);
> >> 
> >> }
> > 
> > There's a known issue that the function foo takes the slice of
> > stack allocated data. Today some peoples argue that it is
> > unsafe operation and should be disallowed in @safe code.
> > 
> > Kenji Hara
> 
> I think there is consensus that in @safe code this should be
> blocked.

Slicing a static array is exactly the same as taking the address of a local 
variable, except that you then have a length in addition to the address. If 
that slice is assigned to anything which has a lifetime greater than that of 
the static array that was sliced, then the slice will be referring to invalid 
memory. That's clearly @system, and I don't see how anyone could even argue 
otherwise. Yes, there is plenty of code which is currently considered @safe by 
the compiler which will break once slicing a static array is considered 
@system like it needs to be (especially because static arrays are 
unfortunately automatically sliced when they're passed to a function which 
takes a dynamic array - I really wish that that were'n the case), but that 
can't be avoided. So, yes, changing it so that slicing a static array is 
@system will cause annoying code breakage, but I don't see any way around it 
without breaking what @safe means and does.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list