Reuse object memory?

Namespace via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Apr 19 09:04:49 PDT 2015


Is it somehow possible to reuse the memory of an object?

My current idea is:
----
@nogc
T emplace(T, Args...)(ref T obj, auto ref Args args) nothrow if 
(is(T == class)) {
     if (obj is null)
         return null;

     enum size_t SIZE = __traits(classInstanceSize, T);

     void[] buf = (cast(void*) obj)[0 .. SIZE];
     buf = typeid(T).init[];
     //obj = cast(T) buf.ptr;

     static if (args.length)
         obj.__ctor(args);

     return obj;
}

Foo f = new Foo(42);
Foo f2 = emplace(f, 23);
----

But is there a more elegant way to do that? Maybe without calling 
the internal __ctor?

In C++ you can do that:

----
#include <iostream>

class Foo {
public:
	int id;
	
	explicit Foo(int _id) : id(_id) { }
};

int main() {
	Foo* f = new Foo(42);
	std::cout << f << ':' << f->id << std::endl;
	new (f) Foo(23);
	std::cout << f << ':' << f->id << std::endl;
	delete f;
}
----


More information about the Digitalmars-d-learn mailing list