On Sunday, 19 April 2015 at 21:17:18 UTC, Ali Çehreli wrote:
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

I'm sorry if I annoy you, but I would really like to know how you would reuse already instantiated storage of an existing object.

Example code:
----
final class Foo {
    uint id;

    @nogc
    this(uint id) {
        this.id = id;
    }
}

Foo f = new Foo(42);
----

Reply via email to