copy_only_int.h 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. // Copyright 2017 The Chromium 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.
  4. #ifndef BASE_TEST_COPY_ONLY_INT_H_
  5. #define BASE_TEST_COPY_ONLY_INT_H_
  6. namespace base {
  7. // A copy-only (not moveable) class that holds an integer. This is designed for
  8. // testing containers. See also MoveOnlyInt.
  9. class CopyOnlyInt {
  10. public:
  11. explicit CopyOnlyInt(int data = 1) : data_(data) {}
  12. CopyOnlyInt(const CopyOnlyInt& other) : data_(other.data_) { ++num_copies_; }
  13. ~CopyOnlyInt() { data_ = 0; }
  14. friend bool operator==(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) {
  15. return lhs.data_ == rhs.data_;
  16. }
  17. friend bool operator!=(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) {
  18. return !operator==(lhs, rhs);
  19. }
  20. friend bool operator<(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) {
  21. return lhs.data_ < rhs.data_;
  22. }
  23. friend bool operator>(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) {
  24. return rhs < lhs;
  25. }
  26. friend bool operator<=(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) {
  27. return !(rhs < lhs);
  28. }
  29. friend bool operator>=(const CopyOnlyInt& lhs, const CopyOnlyInt& rhs) {
  30. return !(lhs < rhs);
  31. }
  32. int data() const { return data_; }
  33. static void reset_num_copies() { num_copies_ = 0; }
  34. static int num_copies() { return num_copies_; }
  35. private:
  36. volatile int data_;
  37. static int num_copies_;
  38. CopyOnlyInt(CopyOnlyInt&&) = delete;
  39. CopyOnlyInt& operator=(CopyOnlyInt&) = delete;
  40. };
  41. } // namespace base
  42. #endif // BASE_TEST_COPY_ONLY_INT_H_