No, takže, snažil sem se zase o kus vylepšit svůj výtvor a tady je výsledek. Zase SIGSEGV, a tentokrát vím kůli čemu. Selhává mi tam kopírování bufferu. Ale netuším čím to je...ve výsledku je v bufferu změť kravin, a jen dva (z 10) validní objekty. *chjo
module test.main;
import std.stdio;
import std.random;
import std.c.stdlib;
import std.traits;
class example
{
int num;
this(int _num)
{
writeln("example ctor");
num = _num*10;
}
~this()
{
writeln("example dtor");
}
int callee()
{
return num*2;
}
}
struct objectPool(T) if (is(T==class))
{
private byte * buffer;
private long top;
private long size;
enum sizeOfEl = __traits(classInstanceSize,T);
enum elPadding = sizeOfEl % classInstanceAlignment!T;
enum finalElSize = sizeOfEl + elPadding;
this(int dummy)
{
buffer = null;
top = 0;
size = 0;
}
~this()
{
callDtors();
freeBuff();
size = 0;
}
long retSize()
{
return top;
}
T opIndex(long index)
{
return cast(T)(buffer+index*finalElSize);
}
void createInstance(Args...)(Args args)
{
if (top == size)
{
if (top == 0 && size ==0)
{
size = 1;
allocBuff();
ctor(cast(T)buffer,args);
++top;
}
else
{
size *= 2;
byte * temp = cast(byte*)malloc(size*finalElSize);
temp[0..size/2] = buffer[0..size/2];
free(buffer);
buffer = temp;
ctor(cast(T)(buffer+top*finalElSize),args);
++top;
}
}
else
{
ctor(cast(T)(buffer+top*finalElSize),args);
++top;
}
}
void allocBuff()
{
buffer = cast(byte*)malloc(finalElSize*size);
}
void freeBuff()
{
free(buffer);
buffer = null;
}
void callCtors()
{
for (int i=0; i<size;++i)
{
// To samé co dtor
ctor(cast(T)(buffer+i*finalElSize),0);
}
}
void callDtors()
{
for (int i=0; i<top;++i)
{
// každý objekt je reference (degradovaný pointer), tím pádem můžeme jakoukoli adresu
//přetypovat na referenci ukazující na objekt libovolného typu a opačně referenci na pointer
dtor(cast(T)(buffer+i*finalElSize));
}
}
void dtor(T ob)
{
ob.__dtor();
}
void ctor(Args...)(T ob,Args args)
{
// Statická inicializace objektu [vtable + metadata]
byte * chunk = cast(byte*)ob;
chunk[0..sizeOfEl] = T.classinfo.init[0..sizeOfEl];
// Samotné volání konstruktoru
ob.__ctor(args);
}
};
void main()
{
objectPool!example oPool = objectPool!example(0);
foreach (int i;0..10)
oPool.createInstance(i);
writeln("FINALLLLL STAGEE");
foreach (long i;0..40)
writeln(oPool[i].num);
}