Skip to content

Commit

Permalink
Use auto-increment as new object id instead of pointer-hash
Browse files Browse the repository at this point in the history
  • Loading branch information
hollacs committed Dec 26, 2024
1 parent 7d4f762 commit 36a3c87
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 4 deletions.
7 changes: 4 additions & 3 deletions include/oo_manager.h
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ namespace oo
class Manager
{
public:
Manager() : m_object_index(1), m_object_check(false) {}
~Manager();

std::weak_ptr<Class> NewClass(const std::string &name);
Expand All @@ -28,6 +29,7 @@ namespace oo
const Constructor* FindConstructor(std::weak_ptr<Class> cls, int arg_size) const;
const Method* FindMethod(std::weak_ptr<Class> cls, const std::string &name) const;
Variable* FindVariable(std::weak_ptr<Object> obj, const std::string &name);
int FindEmptyObjectID();

const std::unordered_map<std::string, std::shared_ptr<Class>> &GetClasses() const
{
Expand All @@ -42,12 +44,11 @@ namespace oo
void Clear();

static Manager* Instance();

Manager() {}
private:

std::unordered_map<std::string, std::shared_ptr<Class>> m_classes;
std::unordered_map<ObjectHash, std::shared_ptr<Object>> m_objects;
int m_object_index;
bool m_object_check;
};
}

Expand Down
31 changes: 30 additions & 1 deletion oo_manager.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ namespace oo
}
}

auto hash = std::hash<std::shared_ptr<Object>>{}(obj);
auto hash = FindEmptyObjectID();
m_objects.emplace(hash, std::move(obj));
m_object_index++;
return hash;
}

Expand All @@ -44,6 +45,32 @@ namespace oo
m_objects.erase(obj_hash);
}

int Manager::FindEmptyObjectID()
{
if (!m_object_check)
{
if (m_object_index == 0)
{
m_object_check = true;
m_object_index++;

while (m_object_index == 0 || m_objects.find(m_object_index) != m_objects.end())
{
m_object_index++;
}
}
}
else
{
while (m_object_index == 0 || m_objects.find(m_object_index) != m_objects.end())
{
m_object_index++;
}
}

return m_object_index;
}

std::weak_ptr<Class> Manager::ToClass(const std::string &name) const
{
auto iter = m_classes.find(name);
Expand Down Expand Up @@ -122,6 +149,8 @@ namespace oo
{
m_classes.clear();
m_objects.clear();
m_object_index = 1;
m_object_check = false;
}

Manager *Manager::Instance()
Expand Down

0 comments on commit 36a3c87

Please sign in to comment.