comparison base/ById.cpp @ 1752:6d09d68165a4 by-id

Further review of ById: make IDs only available when adding a model to the ById store, not by querying the item directly. This means any id encountered in the wild must have been added to the store at some point (even if later released), which simplifies reasoning about lifecycles
author Chris Cannam
date Fri, 05 Jul 2019 15:28:07 +0100
parents b92bdcd4954b
children b679bae1627b
comparison
equal deleted inserted replaced
1751:77543124651b 1752:6d09d68165a4
57 } 57 }
58 } 58 }
59 } 59 }
60 } 60 }
61 61
62 void add(int id, std::shared_ptr<WithId> item) { 62 int add(std::shared_ptr<WithId> item) {
63 int id = item->getUntypedId();
63 if (id == IdAlloc::NO_ID) { 64 if (id == IdAlloc::NO_ID) {
64 throw std::logic_error("cannot add item with id of NO_ID"); 65 throw std::logic_error("item id should never be NO_ID");
65 } 66 }
66 QMutexLocker locker(&m_mutex); 67 QMutexLocker locker(&m_mutex);
67 if (m_items.find(id) != m_items.end()) { 68 if (m_items.find(id) != m_items.end()) {
68 SVCERR << "ById::add: item with id " << id 69 SVCERR << "ById::add: item with id " << id
69 << " is already recorded (existing item type is " 70 << " is already recorded (existing item type is "
71 << ", proposed is " 72 << ", proposed is "
72 << typeid(*item.get()).name() << ")" << endl; 73 << typeid(*item.get()).name() << ")" << endl;
73 throw std::logic_error("item id is already recorded in add"); 74 throw std::logic_error("item id is already recorded in add");
74 } 75 }
75 m_items[id] = item; 76 m_items[id] = item;
77 return id;
76 } 78 }
77 79
78 void release(int id) { 80 void release(int id) {
79 if (id == IdAlloc::NO_ID) { 81 if (id == IdAlloc::NO_ID) {
80 return; 82 return;
81 } 83 }
84 SVCERR << "ById::release(" << id << ")" << endl;
82 QMutexLocker locker(&m_mutex); 85 QMutexLocker locker(&m_mutex);
83 if (m_items.find(id) == m_items.end()) { 86 if (m_items.find(id) == m_items.end()) {
84 SVCERR << "ById::release: unknown item id " << id << endl; 87 SVCERR << "ById::release: unknown item id " << id << endl;
85 throw std::logic_error("unknown item id in release"); 88 throw std::logic_error("unknown item id in release");
86 } 89 }
103 private: 106 private:
104 mutable QMutex m_mutex; 107 mutable QMutex m_mutex;
105 std::unordered_map<int, std::shared_ptr<WithId>> m_items; 108 std::unordered_map<int, std::shared_ptr<WithId>> m_items;
106 }; 109 };
107 110
108 void 111 int
109 AnyById::add(int id, std::shared_ptr<WithId> item) 112 AnyById::add(std::shared_ptr<WithId> item)
110 { 113 {
111 impl().add(id, item); 114 return impl().add(item);
112 } 115 }
113 116
114 void 117 void
115 AnyById::release(int id) 118 AnyById::release(int id)
116 { 119 {