#include <iostream>
#include <memory>
template<typename F>
[[nodiscard]] auto im_finally(F f, bool active = true) noexcept(noexcept(F(std::move(f)))) {
auto x = [f = std::move(f)](void*){ f(); };
return std::unique_ptr<void, decltype(x)>((void*)(active), std::move(x));
}
inline [[nodiscard]] auto im_test_true() {
return im_finally([]{ std::cout << "true ~dtor" << std::endl; }, true);
}
inline [[nodiscard]] auto im_test_false() {
return im_finally([]{ std::cout << "false ~dtor" << std::endl; }, false);
}
int main() {
if (auto false_guard = im_test_false())
std::cout << "false operator bool()" << std::endl;
if (auto true_guard = im_test_true())
std::cout << "true operator bool()" << std::endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8bWVtb3J5PgoKdGVtcGxhdGU8dHlwZW5hbWUgRj4KW1tub2Rpc2NhcmRdXSBhdXRvIGltX2ZpbmFsbHkoRiBmLCBib29sIGFjdGl2ZSA9IHRydWUpIG5vZXhjZXB0KG5vZXhjZXB0KEYoc3RkOjptb3ZlKGYpKSkpIHsKICBhdXRvIHggPSBbZiA9IHN0ZDo6bW92ZShmKV0odm9pZCopeyBmKCk7IH07CiAgcmV0dXJuIHN0ZDo6dW5pcXVlX3B0cjx2b2lkLCBkZWNsdHlwZSh4KT4oKHZvaWQqKShhY3RpdmUpLCBzdGQ6Om1vdmUoeCkpOwp9CgppbmxpbmUgW1tub2Rpc2NhcmRdXSBhdXRvIGltX3Rlc3RfdHJ1ZSgpIHsKICByZXR1cm4gaW1fZmluYWxseShbXXsgc3RkOjpjb3V0IDw8ICJ0cnVlIH5kdG9yIiA8PCBzdGQ6OmVuZGw7IH0sIHRydWUpOwp9CgppbmxpbmUgW1tub2Rpc2NhcmRdXSBhdXRvIGltX3Rlc3RfZmFsc2UoKSB7CiAgcmV0dXJuIGltX2ZpbmFsbHkoW117IHN0ZDo6Y291dCA8PCAiZmFsc2UgfmR0b3IiIDw8IHN0ZDo6ZW5kbDsgfSwgZmFsc2UpOwp9CgppbnQgbWFpbigpIHsKCWlmIChhdXRvIGZhbHNlX2d1YXJkID0gaW1fdGVzdF9mYWxzZSgpKQoJCXN0ZDo6Y291dCA8PCAiZmFsc2Ugb3BlcmF0b3IgYm9vbCgpIiA8PCBzdGQ6OmVuZGw7CgkJCglpZiAoYXV0byB0cnVlX2d1YXJkID0gaW1fdGVzdF90cnVlKCkpCglzdGQ6OmNvdXQgPDwgInRydWUgb3BlcmF0b3IgYm9vbCgpIiA8PCBzdGQ6OmVuZGw7CgkKCXJldHVybiAwOwp9