onceToken.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Copyright (c) 2016 The ZLToolKit project authors. All Rights Reserved.
  3. *
  4. * This file is part of ZLToolKit(https://github.com/xia-chu/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. using namespace std;
  15. namespace toolkit {
  16. class onceToken {
  17. public:
  18. typedef function<void(void)> task;
  19. template<typename FUNC>
  20. onceToken(const FUNC &onConstructed, function<void(void)> onDestructed = nullptr) {
  21. onConstructed();
  22. _onDestructed = std::move(onDestructed);
  23. }
  24. onceToken(nullptr_t, function<void(void)> onDestructed = nullptr) {
  25. _onDestructed = std::move(onDestructed);
  26. }
  27. ~onceToken() {
  28. if (_onDestructed) {
  29. _onDestructed();
  30. }
  31. }
  32. private:
  33. onceToken() = delete;
  34. onceToken(const onceToken &) = delete;
  35. onceToken(onceToken &&) = delete;
  36. onceToken &operator=(const onceToken &) = delete;
  37. onceToken &operator=(onceToken &&) = delete;
  38. private:
  39. task _onDestructed;
  40. };
  41. } /* namespace toolkit */
  42. #endif /* UTIL_ONCETOKEN_H_ */