onceToken.h 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/ZLMediaKit/ZLToolKit).
  5. *
  6. * Use of this source code is governed by MIT license that can be found in the
  7. * LICENSE file in the root of the source tree. All contributing project authors
  8. * may be found in the AUTHORS file in the root of the source tree.
  9. */
  10. #ifndef UTIL_ONCETOKEN_H_
  11. #define UTIL_ONCETOKEN_H_
  12. #include <functional>
  13. #include <type_traits>
  14. namespace toolkit {
  15. class onceToken {
  16. public:
  17. using task = std::function<void(void)>;
  18. template<typename FUNC>
  19. onceToken(const FUNC &onConstructed, task onDestructed = nullptr) {
  20. onConstructed();
  21. _onDestructed = std::move(onDestructed);
  22. }
  23. onceToken(std::nullptr_t, task onDestructed = nullptr) {
  24. _onDestructed = std::move(onDestructed);
  25. }
  26. ~onceToken() {
  27. if (_onDestructed) {
  28. _onDestructed();
  29. }
  30. }
  31. private:
  32. onceToken() = delete;
  33. onceToken(const onceToken &) = delete;
  34. onceToken(onceToken &&) = delete;
  35. onceToken &operator=(const onceToken &) = delete;
  36. onceToken &operator=(onceToken &&) = delete;
  37. private:
  38. task _onDestructed;
  39. };
  40. } /* namespace toolkit */
  41. #endif /* UTIL_ONCETOKEN_H_ */