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?
The best - is always the opinion based solution.
In the common practice, if you use OOP and want to reset the object, write the Reset function, which would do exactly what you want in the exact manner you want it to be done.
You have base classes, so you can provide the same pattern without breaking encapsulation or making fragile, misleading solutions.
p.s. RAII vs zombie
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With