Nameless Static Array

Adam D. Ruppe via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 12 09:17:52 PDT 2014


On Thursday, 12 June 2014 at 16:08:49 UTC, Taylor Hillegeist 
wrote:
> I am considering having different sized arrays for the buffer. 
> I just figured that meant having different structs with various 
> sizes.

You might be able to do it with a templated struct and alias 
this. Check this out:

struct R_Buffer {
    int[] buffer;
}

struct R_Buffer_Sized(size_t bufferSize) {
    int[bufferSize] buffer;
    R_Buffer getGenericBuffer() { return R_Buffer(buffer[]); }
    alias getGenericBuffer this;
}

usage:

R_Buffer_Sized!48 buffer;

then you can pass buffer to any function expecting a regular 
R_Buffer and it will just work. Be careful not to store the 
buffer though, since it is stack allocated, escaping a reference 
to it will lead to crashes.



That's also the reason why something like this is a bit 
problematic:
         R_R_Buffer RRB=R_R_Buffer(uint[12]);

What's the lifetime of the uint[12]? It is in the scope of the 
function call only, so if this were allowed, the compiler might 
consider it a temporary... and then you'd escape a reference to 
it and get corrupted data.

Putting the buffer up top as a separate variable at least gives 
it a clear lifetime scope.


More information about the Digitalmars-d-learn mailing list