17 #include <unordered_map> 24 static int nextId = 0;
26 QMutexLocker locker(&mutex);
28 if (nextId == INT_MAX) {
32 if (nextId == 0 || nextId ==
NO_ID) {
33 throw std::runtime_error(
"Internal ID limit exceeded!");
42 #pragma clang diagnostic ignored "-Wpotentially-evaluated-expression" 49 QMutexLocker locker(&m_mutex);
51 for (
const auto &p: m_items) {
52 if (p.second && p.second.use_count() > 0) {
58 SVCERR <<
"WARNING: ById map is not empty at close; some items have not been released" << endl;
59 SVCERR <<
" Unreleased items are:" << endl;
60 for (
const auto &p: m_items) {
62 if (ptr && ptr.use_count() > 0) {
63 QString message = QString(
"id #%1: type %2")
64 .arg(p.first).arg(
typeid(*ptr.get()).name());
65 if (
auto qobj = std::dynamic_pointer_cast<QObject>(ptr)) {
66 message += QString(
", object name \"%1\"")
67 .arg(qobj->objectName());
69 message += QString(
", use count %1").arg(ptr.use_count());
70 SVCERR <<
" - " << message << endl;
76 int add(std::shared_ptr<WithId> item) {
77 int id = item->getUntypedId();
79 throw std::logic_error(
"item id should never be NO_ID");
82 SVCERR <<
"ById::add(#" <<
id <<
") of type " 83 <<
typeid(*item.get()).name() << endl;
85 QMutexLocker locker(&m_mutex);
86 if (m_items.find(
id) != m_items.end()) {
87 SVCERR <<
"ById::add: item with id " <<
id 88 <<
" is already recorded (existing item type is " 89 <<
typeid(*m_items.find(
id)->second.get()).name()
91 <<
typeid(*item.get()).name() <<
")" << endl;
92 throw std::logic_error(
"item id is already recorded in add");
103 SVCERR <<
"ById::release(#" <<
id <<
")" << endl;
105 QMutexLocker locker(&m_mutex);
106 if (m_items.find(
id) == m_items.end()) {
107 SVCERR <<
"ById::release: unknown item id " <<
id << endl;
108 throw std::logic_error(
"unknown item id in release");
113 std::shared_ptr<WithId>
get(
int id)
const {
117 QMutexLocker locker(&m_mutex);
118 const auto &itr = m_items.find(
id);
119 if (itr != m_items.end()) {
128 std::unordered_map<int, std::shared_ptr<WithId>>
m_items;
134 return impl().add(item);
143 std::shared_ptr<WithId>
146 return impl().get(
id);
int add(std::shared_ptr< WithId > item)
static std::shared_ptr< WithId > get(int)
static int add(std::shared_ptr< WithId >)
std::unordered_map< int, std::shared_ptr< WithId > > m_items