Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class Resource {
- public:
- Resource() {
- cout << "Resource created\n";
- }
- ~Resource() {
- cout << "Resource deleted\n";
- }
- };
- void makeResourceByArgument(Resource ** rs) {
- *rs = new Resource();
- }
- void resourceDeleter(Resource * rs) {
- delete rs;
- }
- template<typename resource_t>
- class CallbackOnOutOfScope {
- using callback_t = void (*)(resource_t*);
- resource_t * m_resource;
- callback_t m_callback;
- public:
- explicit CallbackOnOutOfScope(callback_t callback)
- : m_resource{ nullptr }, m_callback{ callback }
- {}
- ~CallbackOnOutOfScope() noexcept {
- m_callback(m_resource);
- }
- void operator=(resource_t * resource) { m_resource = resource; }
- resource_t operator*() { return *m_resource; }
- CallbackOnOutOfScope(const CallbackOnOutOfScope &) = delete;
- CallbackOnOutOfScope(const CallbackOnOutOfScope &&) = delete;
- CallbackOnOutOfScope & operator=(const CallbackOnOutOfScope &) = delete;
- CallbackOnOutOfScope & operator=(const CallbackOnOutOfScope &&) = delete;
- };
- int main() {
- cout << "Before scope\n";
- {
- cout << "Scope start\n";
- CallbackOnOutOfScope<Resource> resource(resourceDeleter);
- makeResourceByArgument(reinterpret_cast<Resource**>(&resource));
- cout << "Scope end\n";
- }
- cout << "After scope\n";
- return 0;
- }
Add Comment
Please, Sign In to add comment