add leak checker for nf7::Context

This commit is contained in:
falsycat 2022-11-15 15:41:48 +09:00
parent 77ac2e95c0
commit 00d9697b9d
3 changed files with 20 additions and 0 deletions

14
main.cc
View File

@ -170,6 +170,11 @@ class Env final : public nf7::Env {
}
}
}
~Env() noexcept {
if (ctx_cnt_ > 0) {
std::cout << "context leak detected: " << ctx_cnt_ << std::endl;
}
}
void TearDownRoot() noexcept {
if (root_) {
@ -270,6 +275,13 @@ class Env final : public nf7::Env {
files_.erase(id);
}
void AddContext(nf7::Context&) noexcept override {
++ctx_cnt_;
}
void RemoveContext(nf7::Context&) noexcept override {
--ctx_cnt_;
}
void AddWatcher(nf7::File::Id id, nf7::Env::Watcher& w) noexcept override {
watchers_[id].push_back(&w);
}
@ -293,6 +305,8 @@ class Env final : public nf7::Env {
std::unordered_map<nf7::File::Id, nf7::File*> files_;
std::unordered_map<nf7::File::Id, std::vector<nf7::Env::Watcher*>> watchers_;
std::atomic<size_t> ctx_cnt_ = 0;
};

2
nf7.cc
View File

@ -254,8 +254,10 @@ Context::Context(File& f, const std::shared_ptr<Context>& parent) noexcept :
Context::Context(Env& env, File::Id initiator, const std::shared_ptr<Context>& parent) noexcept :
env_(&env), initiator_(initiator),
parent_(parent), depth_(parent? parent->depth()+1: 0) {
env_->AddContext(*this);
}
Context::~Context() noexcept {
env_->RemoveContext(*this);
}
File& Env::GetFileOrThrow(File::Id id) const {

4
nf7.hh
View File

@ -301,6 +301,10 @@ class Env {
virtual File::Id AddFile(File&) noexcept = 0;
virtual void RemoveFile(File::Id) noexcept = 0;
friend class nf7::Context;
virtual void AddContext(nf7::Context&) noexcept = 0;
virtual void RemoveContext(nf7::Context&) noexcept = 0;
virtual void AddWatcher(File::Id, Watcher&) noexcept = 0;
virtual void RemoveWatcher(File::Id, Watcher&) noexcept = 0;