Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
2.0KB

  1. /* Copyright 2016, Ableton AG, Berlin. All rights reserved.
  2. *
  3. * This program is free software: you can redistribute it and/or modify
  4. * it under the terms of the GNU General Public License as published by
  5. * the Free Software Foundation, either version 2 of the License, or
  6. * (at your option) any later version.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public License
  14. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  15. *
  16. * If you would like to incorporate Link into a proprietary software application,
  17. * please contact <link-devs@ableton.com>.
  18. */
  19. #pragma once
  20. #include <memory>
  21. namespace ableton
  22. {
  23. namespace util
  24. {
  25. // A utility handler for passing to async functions that may call the
  26. // handler past the lifetime of the wrapped delegate object.
  27. // The need for this is particularly driven by boost::asio timer
  28. // objects, which explicitly document that they may be called without
  29. // an error code after they have been cancelled. This has led to
  30. // several crashes. This handler wrapper implements a useful idiom for
  31. // avoiding this problem.
  32. template <typename Delegate>
  33. struct SafeAsyncHandler
  34. {
  35. SafeAsyncHandler(const std::shared_ptr<Delegate>& pDelegate)
  36. : mpDelegate(pDelegate)
  37. {
  38. }
  39. template <typename... T>
  40. void operator()(T&&... t) const
  41. {
  42. std::shared_ptr<Delegate> pDelegate = mpDelegate.lock();
  43. if (pDelegate)
  44. {
  45. (*pDelegate)(std::forward<T>(t)...);
  46. }
  47. }
  48. std::weak_ptr<Delegate> mpDelegate;
  49. };
  50. // Factory function for easily wrapping a shared_ptr to a handler
  51. template <typename Delegate>
  52. SafeAsyncHandler<Delegate> makeAsyncSafe(const std::shared_ptr<Delegate>& pDelegate)
  53. {
  54. return {pDelegate};
  55. }
  56. } // namespace util
  57. } // namespace ableton