add LeakDetector
This commit is contained in:
parent
2c671d65c4
commit
51b550ae26
@ -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
|
||||
|
45
iface/common/leak_detector.hh
Normal file
45
iface/common/leak_detector.hh
Normal 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
|
21
iface/common/leak_detector_test.cc
Normal file
21
iface/common/leak_detector_test.cc
Normal 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
|
Loading…
x
Reference in New Issue
Block a user