1 // Copyright 2017 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_TEST_COPY_ONLY_INT_H_ 6 #define BASE_TEST_COPY_ONLY_INT_H_ 7 8 #include <utility> 9 10 #include "base/functional/callback.h" 11 #include "third_party/abseil-cpp/absl/cleanup/cleanup.h" 12 13 namespace base { 14 15 // A copy-only (not moveable) class that holds an integer. This is designed for 16 // testing containers. See also MoveOnlyInt. 17 class CopyOnlyInt { 18 public: data_(data)19 explicit CopyOnlyInt(int data = 1) : data_(data) {} CopyOnlyInt(const CopyOnlyInt & other)20 CopyOnlyInt(const CopyOnlyInt& other) : data_(other.data_) { ++num_copies_; } 21 ~CopyOnlyInt(); 22 23 friend bool operator==(const CopyOnlyInt& lhs, 24 const CopyOnlyInt& rhs) = default; 25 friend auto operator<=>(const CopyOnlyInt& lhs, 26 const CopyOnlyInt& rhs) = default; 27 data()28 int data() const { return data_; } 29 reset_num_copies()30 static void reset_num_copies() { num_copies_ = 0; } 31 num_copies()32 static int num_copies() { return num_copies_; } 33 34 // Called with the value of `data()` when an instance of `CopyOnlyInt` is 35 // destroyed. Returns an `absl::Cleanup` scoper that automatically 36 // unregisters the callback when the scoper is destroyed. SetScopedDestructionCallback(RepeatingCallback<void (int)> callback)37 static auto SetScopedDestructionCallback( 38 RepeatingCallback<void(int)> callback) { 39 GetDestructionCallbackStorage() = std::move(callback); 40 return absl::Cleanup([] { GetDestructionCallbackStorage().Reset(); }); 41 } 42 43 private: 44 static RepeatingCallback<void(int)>& GetDestructionCallbackStorage(); 45 46 volatile int data_; 47 48 static int num_copies_; 49 50 CopyOnlyInt(CopyOnlyInt&&) = delete; 51 CopyOnlyInt& operator=(CopyOnlyInt&) = delete; 52 }; 53 54 } // namespace base 55 56 #endif // BASE_TEST_COPY_ONLY_INT_H_ 57