fix(BytePatch): To ensure proper cleanup make use of unique_ptr (#491)

This commit is contained in:
Yimura 2022-10-21 14:09:20 +02:00 committed by GitHub
parent 657d292e07
commit 70d604a535
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -10,32 +10,24 @@ namespace memory
memcpy(m_address, m_original_bytes.data(), m_original_bytes.size()); memcpy(m_address, m_original_bytes.data(), m_original_bytes.size());
} }
/// <summary>
/// To guarantee proper restoration of bytes all shared_ptr instances will be invalidated that point to this object.
/// </summary>
void restore() const void restore() const
{ {
if (const auto it = std::find(m_patches.begin(), m_patches.end(), this); it != m_patches.end()) if (const auto it = std::find(m_patches.begin(), m_patches.end(), this); it != m_patches.end())
{ {
it->reset();
m_patches.erase(it); m_patches.erase(it);
} }
} }
template <typename TAddr> template <typename TAddr>
static std::shared_ptr<byte_patch> make(TAddr address, std::remove_pointer_t<std::remove_reference_t<TAddr>> value) static const std::unique_ptr<byte_patch>& make(TAddr address, std::remove_pointer_t<std::remove_reference_t<TAddr>> value)
{ {
auto patch = std::shared_ptr<byte_patch>(new byte_patch(address, value)); return m_patches.emplace_back(
m_patches.emplace_back(patch); std::unique_ptr<byte_patch>(new byte_patch(address, value)));
return patch;
} }
static void restore_all() static void restore_all()
{ {
for (const auto& patch : m_patches) m_patches.clear();
{
patch->restore();
}
} }
private: private:
@ -51,16 +43,16 @@ namespace memory
} }
protected: protected:
static inline std::vector<std::shared_ptr<byte_patch>> m_patches; static inline std::vector<std::unique_ptr<byte_patch>> m_patches;
private: private:
void* m_address; void* m_address;
std::vector<uint8_t> m_original_bytes; std::vector<uint8_t> m_original_bytes;
friend bool operator== (const std::shared_ptr<byte_patch> a, const byte_patch* b); friend bool operator== (const std::unique_ptr<byte_patch>& a, const byte_patch* b);
}; };
bool operator== (const std::shared_ptr<byte_patch> a, const byte_patch* b) bool operator== (const std::unique_ptr<byte_patch>& a, const byte_patch* b)
{ {
return a->m_address == b->m_address; return a->m_address == b->m_address;
} }