Guest User

Untitled

a guest
Oct 18th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.92 KB | None | 0 0
  1. //This example demostrate the gist of why higher order function can be more save
  2. //1. Higher order functions are the functions that take a function as param or return a function
  3. //2. Higher order functions take care of the safty by automatically doing some safe check before
  4. // invoking some user-defined function, thus avoid undefined behaviors.
  5. //3. Similar functionality can be applied to automatically check if pointer is valid before using
  6. // a unique pointer.
  7.  
  8. #include <mutex>
  9.  
  10. template <typename T>
  11. class Lock
  12. {
  13. T* m_data;
  14. std::mutex m_mutex;
  15.  
  16. public:
  17. template <typename F>
  18. decltype(auto) access(F&& func)
  19. {
  20. std::lock_guard lock_guard(m_mutex);
  21. // make sure the mutex is locked before manipulating the resource
  22. return std::forward<decltype(func)>(func)(m_data);
  23. }
  24. };
  25.  
  26.  
  27.  
  28. int main()
  29. {
  30. Lock<int> resource_manager;
  31. resource_manager.access([](int* data){data = new int;});
  32. }
Add Comment
Please, Sign In to add comment