D needs emplacement new
Adam D. Ruppe via Digitalmars-d
digitalmars-d at puremagic.com
Sat Apr 25 11:46:51 PDT 2015
You could just call the constructor again to reuse an object. I
guess you should also reinitialize the memory, but that's pretty
easy too.
Instead of placement new to reuse an object, make a function like
reset() or reinitialize() that destructs the first, then copies
the init back over and calls the constructor again.
Something like this:
void reinitialize(ClassName, CtorArgs...)(ClassName obj, CtorArgs
args) {
assert(typeid(obj) == typeid(ClassName),
"Don't use this on interfaces or base classes!");
static if(__traits(hasMember, obj, "__dtor"))
obj.__dtor();
(cast(void*) obj)[0 .. typeid(obj).init.length] =
typeid(obj).init[];
static if(__traits(hasMember, obj, "__ctor"))
obj.__ctor(args);
}
Then, you create it however up front and just reinitialize it
when you're all set. I think that is a bit clearer in meaning
than placement new as well.
More information about the Digitalmars-d
mailing list