util.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Copyright 2013 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 TOOLS_ANDROID_FORWARDER2_UTIL_H_
  5. #define TOOLS_ANDROID_FORWARDER2_UTIL_H_
  6. #include "base/check.h"
  7. #include <utility>
  8. namespace forwarder2 {
  9. // Safely deletes a ref-counted value in a provided map by unlinking the object
  10. // from the map before deleting it in case its destructor would access the map.
  11. // Deletion will only happen by definition if the object's refcount is set to 1
  12. // before this function gets called. Returns whether the element could be found
  13. // in the map.
  14. template <typename Map, typename K>
  15. bool DeleteRefCountedValueInMap(const K& key, Map* map) {
  16. const typename Map::iterator it = map->find(key);
  17. if (it == map->end())
  18. return false;
  19. DeleteRefCountedValueInMapFromIterator(it, map);
  20. return true;
  21. }
  22. // See DeleteRefCountedValueInMap() above.
  23. template <typename Map, typename Iterator>
  24. void DeleteRefCountedValueInMapFromIterator(Iterator it, Map* map) {
  25. DCHECK(it != map->end());
  26. const typename Map::value_type::second_type smart_pointer =
  27. std::move(it->second);
  28. map->erase(it);
  29. }
  30. } // namespace forwarder2
  31. #endif // TOOLS_ANDROID_FORWARDER2_UTIL_H_