I need some pattern or rather proper name for next thing. I'm pretty sure it's not new, but I'd just suffered fiasco looking it in nets.
I need to setup and then relax some mode automatically by the end of function.
I provide lambdas for 'setup' and 'relax' actions into special 'Affector' object (or whatever name it has).
- First one is called during construction,
- and the second is called during destruction.
Thus even if I have an exception, or place 'return' statement somewhere in the middle, I still can be sure, that mode will be relaxed afterall.
Here is example of 'affector' thing:
class Affector {
public:
Affector(
std::function<void()> affect,
std::function<void()> relax
) : Relax(relax) {
affect();
};
~Affector() { Relax(); }
protected:
std::function<void()> Relax;
};
Example of use:
void Foo(MyObject *obj) {
// During construction 'affector' sets 'some' mode,
// we want to relax by the end of Foo.
Affector affector(
[obj] { obj->setSomeMode(true); },
[obj] { obj->setSomeMode(false); }
);
obj->doSomething();
// Here 'affector' relaxes 'some' mode during its destruction stage.
}
Aucun commentaire:
Enregistrer un commentaire