Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //This example demostrate the gist of why higher order function can be more save
- //1. Higher order functions are the functions that take a function as param or return a function
- //2. Higher order functions take care of the safty by automatically doing some safe check before
- // invoking some user-defined function, thus avoid undefined behaviors.
- //3. Similar functionality can be applied to automatically check if pointer is valid before using
- // a unique pointer.
- #include <mutex>
- template <typename T>
- class Lock
- {
- T* m_data;
- std::mutex m_mutex;
- public:
- template <typename F>
- decltype(auto) access(F&& func)
- {
- std::lock_guard lock_guard(m_mutex);
- // make sure the mutex is locked before manipulating the resource
- return std::forward<decltype(func)>(func)(m_data);
- }
- };
- int main()
- {
- Lock<int> resource_manager;
- resource_manager.access([](int* data){data = new int;});
- }
Add Comment
Please, Sign In to add comment