作者: 谢瑞阳 10225101483 徐翔宇 10225101535
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.

47 rivejä
1.5 KiB

  1. // Copyright (c) 2018 The LevelDB Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file. See the AUTHORS file for names of contributors.
  4. #ifndef STORAGE_LEVELDB_UTIL_NO_DESTRUCTOR_H_
  5. #define STORAGE_LEVELDB_UTIL_NO_DESTRUCTOR_H_
  6. #include <type_traits>
  7. #include <utility>
  8. namespace leveldb {
  9. // Wraps an instance whose destructor is never called.
  10. //
  11. // This is intended for use with function-level static variables.
  12. template<typename InstanceType>
  13. class NoDestructor {
  14. public:
  15. template <typename... ConstructorArgTypes>
  16. explicit NoDestructor(ConstructorArgTypes&&... constructor_args) {
  17. static_assert(sizeof(instance_storage_) >= sizeof(InstanceType),
  18. "instance_storage_ is not large enough to hold the instance");
  19. static_assert(
  20. alignof(decltype(instance_storage_)) >= alignof(InstanceType),
  21. "instance_storage_ does not meet the instance's alignment requirement");
  22. new (&instance_storage_) InstanceType(
  23. std::forward<ConstructorArgTypes>(constructor_args)...);
  24. }
  25. ~NoDestructor() = default;
  26. NoDestructor(const NoDestructor&) = delete;
  27. NoDestructor& operator=(const NoDestructor&) = delete;
  28. InstanceType* get() {
  29. return reinterpret_cast<InstanceType*>(&instance_storage_);
  30. }
  31. private:
  32. typename
  33. std::aligned_storage<sizeof(InstanceType), alignof(InstanceType)>::type
  34. instance_storage_;
  35. };
  36. } // namespace leveldb
  37. #endif // STORAGE_LEVELDB_UTIL_NO_DESTRUCTOR_H_