Reuse object memory?
Ali Çehreli via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Apr 19 14:17:17 PDT 2015
On 04/19/2015 09:04 AM, Namespace wrote:
> Is it somehow possible to reuse the memory of an object?
Yes, when you cast a class variable to void*, you get the address of the
object.
> @nogc
> T emplace(T, Args...)(ref T obj, auto ref Args args) nothrow if (is(T ==
> class)) {
There is already std.conv.emplace:
import std.conv;
import core.memory;
class Foo
{
int i;
this(int i)
{
this.i = i;
}
}
void main()
{
void* buffer = GC.calloc(1234);
enum FooSize = __traits(classInstanceSize, Foo);
/* These two object are constructed on a void[] slice: */
auto f = emplace!Foo(buffer[0..FooSize], 42);
auto f2 = emplace!Foo(buffer[0..FooSize], 43);
/* f3 is constructed on top of an existing object: */
auto f2_addr = cast(void*)f2;
auto f3 = emplace!Foo(f2_addr[0..FooSize], 44);
/* At this point, all three reference the same object: */
assert(&f.i == &f2.i);
assert(&f.i == &f3.i);
}
Ali
More information about the Digitalmars-d-learn
mailing list