From 883ef12c7f377cf2f134a2659349a08500a395a2 Mon Sep 17 00:00:00 2001 From: Thomas Goyne Date: Sat, 1 Aug 2015 15:31:45 -0700 Subject: [PATCH] Add Realm::close() and call it in RealmCache::clear() This is needed for the Swift tests due to that throwing an exception over Swift code unavoidably results in objects being leaked. --- shared_realm.cpp | 23 +++++++++++++++++++++++ shared_realm.hpp | 4 ++++ 2 files changed, 27 insertions(+) diff --git a/shared_realm.cpp b/shared_realm.cpp index 6d57f111..c87dd5d4 100644 --- a/shared_realm.cpp +++ b/shared_realm.cpp @@ -374,6 +374,22 @@ uint64_t Realm::get_schema_version(const realm::Realm::Config &config) return ObjectStore::get_schema_version(Realm(config).read_group()); } +void Realm::close() +{ + invalidate(); + + if (m_notifier) { + m_notifier->remove_realm(this); + } + + m_group = nullptr; + m_shared_group = nullptr; + m_history = nullptr; + m_read_only_group = nullptr; + m_notifier = nullptr; + m_binding_context = nullptr; +} + SharedRealm RealmCache::get_realm(const std::string &path, std::thread::id thread_id) { std::lock_guard lock(m_mutex); @@ -446,6 +462,13 @@ void RealmCache::cache_realm(SharedRealm &realm, std::thread::id thread_id) void RealmCache::clear() { std::lock_guard lock(m_mutex); + for (auto const& path : m_cache) { + for (auto const& thread : path.second) { + if (auto realm = thread.second.lock()) { + realm->close(); + } + } + } m_cache.clear(); } diff --git a/shared_realm.hpp b/shared_realm.hpp index e6c94fc2..81b14bf7 100644 --- a/shared_realm.hpp +++ b/shared_realm.hpp @@ -101,6 +101,10 @@ namespace realm { std::thread::id thread_id() const { return m_thread_id; } void verify_thread() const; + // Close this Realm and remove it from the cache. Continuing to use a + // Realm after closing it will produce undefined behavior. + void close(); + ~Realm(); private: