I have an instance of a class object that I want to reset to its original state. and it has a well tested constructor. Normally I would do this with code like
myObject = MyObject{};
but the temporary object is too large to fit on the stack.
My options are
1) Create a default temporary object on the heap
auto* tempObject = make_unique<MyObject>();
myObject = *tempObject;
2) Destroy and reconstruct in place with placement new
myObject.~MyObject();
new( &myObject) MyObject();
3) Refactor constructor code into a separate reset function that is called from the constructor and from anywhere else.
MyObject::MyObject()
{
reset();
}
//and
myObject.reset();
I don't like any of the options particularly: 1) allocates on the heap in a project that tries to avoid unnecessary allocations 2) is fragile and smelly Can I use placement new(this) in operator=? 3) I'm lazy and want to avoid refactoring if I can.
I guess what I'm really asking is are there other ways I've missed? Ideally Is there some sort of optimisation that could apply that means the compiler can elide creating the temporary item on the stack and allow me to use my original code?