00001 // Copyright 2018 The Abseil Authors. 00002 // 00003 // Licensed under the Apache License, Version 2.0 (the "License"); 00004 // you may not use this file except in compliance with the License. 00005 // You may obtain a copy of the License at 00006 // 00007 // https://www.apache.org/licenses/LICENSE-2.0 00008 // 00009 // Unless required by applicable law or agreed to in writing, software 00010 // distributed under the License is distributed on an "AS IS" BASIS, 00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 00012 // See the License for the specific language governing permissions and 00013 // limitations under the License. 00014 00015 #ifndef ABSL_CONTAINER_INTERNAL_TRACKED_H_ 00016 #define ABSL_CONTAINER_INTERNAL_TRACKED_H_ 00017 00018 #include <stddef.h> 00019 #include <memory> 00020 #include <utility> 00021 00022 namespace absl { 00023 namespace container_internal { 00024 00025 // A class that tracks its copies and moves so that it can be queried in tests. 00026 template <class T> 00027 class Tracked { 00028 public: 00029 Tracked() {} 00030 // NOLINTNEXTLINE(runtime/explicit) 00031 Tracked(const T& val) : val_(val) {} 00032 Tracked(const Tracked& that) 00033 : val_(that.val_), 00034 num_moves_(that.num_moves_), 00035 num_copies_(that.num_copies_) { 00036 ++(*num_copies_); 00037 } 00038 Tracked(Tracked&& that) 00039 : val_(std::move(that.val_)), 00040 num_moves_(std::move(that.num_moves_)), 00041 num_copies_(std::move(that.num_copies_)) { 00042 ++(*num_moves_); 00043 } 00044 Tracked& operator=(const Tracked& that) { 00045 val_ = that.val_; 00046 num_moves_ = that.num_moves_; 00047 num_copies_ = that.num_copies_; 00048 ++(*num_copies_); 00049 } 00050 Tracked& operator=(Tracked&& that) { 00051 val_ = std::move(that.val_); 00052 num_moves_ = std::move(that.num_moves_); 00053 num_copies_ = std::move(that.num_copies_); 00054 ++(*num_moves_); 00055 } 00056 00057 const T& val() const { return val_; } 00058 00059 friend bool operator==(const Tracked& a, const Tracked& b) { 00060 return a.val_ == b.val_; 00061 } 00062 friend bool operator!=(const Tracked& a, const Tracked& b) { 00063 return !(a == b); 00064 } 00065 00066 size_t num_copies() { return *num_copies_; } 00067 size_t num_moves() { return *num_moves_; } 00068 00069 private: 00070 T val_; 00071 std::shared_ptr<size_t> num_moves_ = std::make_shared<size_t>(0); 00072 std::shared_ptr<size_t> num_copies_ = std::make_shared<size_t>(0); 00073 }; 00074 00075 } // namespace container_internal 00076 } // namespace absl 00077 00078 #endif // ABSL_CONTAINER_INTERNAL_TRACKED_H_