tracked.h 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2018 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef ABSL_CONTAINER_INTERNAL_TRACKED_H_
  15. #define ABSL_CONTAINER_INTERNAL_TRACKED_H_
  16. #include <stddef.h>
  17. #include <memory>
  18. #include <utility>
  19. #include "absl/base/config.h"
  20. namespace absl {
  21. ABSL_NAMESPACE_BEGIN
  22. namespace container_internal {
  23. // A class that tracks its copies and moves so that it can be queried in tests.
  24. template <class T>
  25. class Tracked {
  26. public:
  27. Tracked() {}
  28. // NOLINTNEXTLINE(runtime/explicit)
  29. Tracked(const T& val) : val_(val) {}
  30. Tracked(const Tracked& that)
  31. : val_(that.val_),
  32. num_moves_(that.num_moves_),
  33. num_copies_(that.num_copies_) {
  34. ++(*num_copies_);
  35. }
  36. Tracked(Tracked&& that)
  37. : val_(std::move(that.val_)),
  38. num_moves_(std::move(that.num_moves_)),
  39. num_copies_(std::move(that.num_copies_)) {
  40. ++(*num_moves_);
  41. }
  42. Tracked& operator=(const Tracked& that) {
  43. val_ = that.val_;
  44. num_moves_ = that.num_moves_;
  45. num_copies_ = that.num_copies_;
  46. ++(*num_copies_);
  47. }
  48. Tracked& operator=(Tracked&& that) {
  49. val_ = std::move(that.val_);
  50. num_moves_ = std::move(that.num_moves_);
  51. num_copies_ = std::move(that.num_copies_);
  52. ++(*num_moves_);
  53. }
  54. const T& val() const { return val_; }
  55. friend bool operator==(const Tracked& a, const Tracked& b) {
  56. return a.val_ == b.val_;
  57. }
  58. friend bool operator!=(const Tracked& a, const Tracked& b) {
  59. return !(a == b);
  60. }
  61. size_t num_copies() { return *num_copies_; }
  62. size_t num_moves() { return *num_moves_; }
  63. private:
  64. T val_;
  65. std::shared_ptr<size_t> num_moves_ = std::make_shared<size_t>(0);
  66. std::shared_ptr<size_t> num_copies_ = std::make_shared<size_t>(0);
  67. };
  68. } // namespace container_internal
  69. ABSL_NAMESPACE_END
  70. } // namespace absl
  71. #endif // ABSL_CONTAINER_INTERNAL_TRACKED_H_