Am 14.06.2011 08:55, schrieb Petr Janda: > I see. Thank you. > > I do have a couple of questions about myNew and myDelete though. > > T ret = emplace!(T, Args)(objMem, args); > return ret; // return new custom allocated Object > > So emplace runs the constructor of T. > > 1) Does emplace return a copy of T?
T is a class, not an object, so it can't return "a copy". What emplace does is that it creates an object in the given memory (objMem[] in my example), i.e. it initializes the memory and runs the given constructor on it - just like new does with memory from the heap that it allocates itself. See also http://d-programming-language.org/phobos/std_conv.html#emplace for a description of emplace (I used the "T emĀplace(T, Args...)(void[] chunk, Args args);" version). > 2) Is Object "ret" constructed as a copy(via copy constructor) of > what emplace returns? > 3) Is there some kind of internal reference counting/smart pointer > happening that I can't see? No, not at all. My example just gets memory from the C heap (via malloc()), "makes it an object" with emplace (this means, it will contain all data an object created by new would contain) and returns that object. Just like in C++ you have to delete it (with myDelete) to prevent memory leaks. You could of course implement reference counting yourself, maybe with a custom class and a custom myNew that creates objects of that class and initializes the reference counter or something. > > And about myDelete: > > core.stdc.stdlib.free(cast(void*)obj); > > Casting object to a pointer to a heap allocated memory? That's neat! malloc() returned a void pointer (that was casted to void[] and then made an object with emplace). By casting the Object to void* we get a pointer pointing with the same value as the one returned by malloc() before, so we can call free() on it. But before that, clear() is used, so the Object's destructor is called. Also note that malloc() and free() were just examples, you could also use chunks of memory obtained by other means (like mmap) with emplace. Cheers, - Daniel
