add LeakDetector

This commit is contained in:
falsycat 2023-08-06 10:31:04 +09:00
parent 2c671d65c4
commit 51b550ae26
3 changed files with 68 additions and 0 deletions

View File

@ -13,6 +13,7 @@ target_sources(nf7_iface
common/container.hh
common/exception.hh
common/future.hh
common/leak_detector.hh
common/observer.hh
common/task.hh
common/task_context.hh
@ -33,6 +34,7 @@ target_sources(nf7_iface_test
common/dealer_test.cc
common/container_test.cc
common/future_test.cc
common/leak_detector_test.cc
common/observer_test.cc
common/observer_test.hh
common/task_test.cc

View File

@ -0,0 +1,45 @@
// No copyright
#pragma once
#include <atomic>
#include <cassert>
#include <cstdint>
#include <cstdlib>
#include <iostream>
namespace nf7 {
#if !defined(NDEBUG)
template <typename T>
class LeakDetector {
public:
LeakDetector() { (void) checker_; ++count_; }
virtual ~LeakDetector() noexcept { --count_; }
private:
struct Checker {
~Checker() {
if (count_ > 0) {
std::cerr << "LEAK DETECTED: " << typeid(T).name() << std::endl;
}
}
};
public:
static uint64_t count() noexcept { return count_; }
private:
static inline Checker checker_;
static inline std::atomic<uint64_t> count_ = 0;
};
#else
template <typename T>
class LeakDetector {
public:
static uint64_t count() noexcept { return 0; }
};
#endif
} // namespace nf7

View File

@ -0,0 +1,21 @@
// No copyright
#include "iface/common/leak_detector.hh"
#include <gtest/gtest.h>
#include <memory>
namespace {
class A : private nf7::LeakDetector<A> { };
} // namespace
#if !defined(NDEBUG)
TEST(LeakDetector, Counter) {
{
A a;
EXPECT_EQ(nf7::LeakDetector<A>::count(), 1);
}
EXPECT_EQ(nf7::LeakDetector<A>::count(), 0);
}
#endif