Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion leetcode/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# 构建测试对象库
file(GLOB_RECURSE TEST_SRC "*.cpp")
add_library(test_leetcode_o OBJECT ${TEST_SRC})
target_include_directories(test_leetcode_o PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/test)
target_include_directories(test_leetcode_o PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/test)
target_compile_definitions(test_leetcode_o PRIVATE PROBLEM_PATH=\"${CMAKE_CURRENT_SOURCE_DIR}\")
target_compile_options(test_leetcode_o PRIVATE -Werror -Wall -Wextra -Wodr)

Expand Down
10 changes: 10 additions & 0 deletions leetcode/list_node.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#pragma once
#include "tracker.hpp"

struct ListNode : public Tracker<ListNode> {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
File renamed without changes.
File renamed without changes.
53 changes: 53 additions & 0 deletions leetcode/tracker.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#pragma once
#include <cassert>
#include <cstddef>
#include <unordered_set>
#include <vector>

template <typename T>
class Tracker {
public:
static void *operator new(std::size_t count) {
assert(count == sizeof(T));
void *ptr{::operator new(count)};
activeObjects_.insert(static_cast<T *>(ptr));
return ptr;
}

static void operator delete(void *ptr) {
assert(ptr != nullptr);
activeObjects_.erase(static_cast<T *>(ptr));
::operator delete(ptr);
}

static void *operator new[](std::size_t count) {
assert(count % sizeof(T) == 0);
void *ptr{::operator new[](count)};
activeArrays_.insert(static_cast<T *>(ptr));
return ptr;
}

static void operator delete[](void *ptr) {
assert(ptr != nullptr);
activeArrays_.erase(static_cast<T *>(ptr));
::operator delete(ptr);
}

static void Clear() {
std::vector<T *> activeObjects(activeObjects_.begin(), activeObjects_.end());
for (T *object : activeObjects) {
delete object;
}
std::vector<T *> activeArrays(activeArrays_.begin(), activeArrays_.end());
for (T *array : activeArrays) {
delete[] array;
}
}

protected:
Tracker() = default;

private:
static inline std::unordered_set<T *> activeObjects_;
static inline std::unordered_set<T *> activeArrays_;
};