copy_only_int.h 1.6 KB

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