On Saturday, 25 April 2015 at 18:46:52 UTC, Adam D. Ruppe wrote:
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.
Nice name, fits better. But that should be in phobos, don't you
think?