Created
March 6, 2019 09:14
-
-
Save igor-egorov/bcb3302997b799160c603ac30245189b to your computer and use it in GitHub Desktop.
Objects Counter C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Copyright Soramitsu Co., Ltd. All Rights Reserved. | |
* SPDX-License-Identifier: Apache-2.0 | |
*/ | |
#ifndef IROHA_OBJ_COUNTER_HPP | |
#define IROHA_OBJ_COUNTER_HPP | |
#include <atomic> | |
#include <iostream> | |
#include <mutex> | |
#include <sstream> | |
template <typename T> | |
struct ObjCounter { | |
static std::atomic<size_t> objects_created; | |
static std::atomic<size_t> objects_alive; | |
ObjCounter() noexcept { | |
objects_created.fetch_add(1, std::memory_order_relaxed); | |
objects_alive.fetch_add(1, std::memory_order_relaxed); | |
std::cout << "\033[1;31m" << typeid(T).name() << " created\033[0m" | |
<< std::endl; | |
} | |
static std::string getStats() { | |
std::lock_guard<std::mutex> lock(get_stats_mu_); | |
std::stringstream ss; | |
ss << typeid(T).name() << ": created " | |
<< objects_created.load(std::memory_order_relaxed) | |
<< ", alive :" << objects_alive.load(std::memory_order_relaxed); | |
return ss.str(); | |
} | |
protected: | |
~ObjCounter() // objects should never be removed through pointers of this | |
// type | |
{ | |
objects_alive.fetch_add(-1, std::memory_order_relaxed); | |
std::cout << "\033[1;31m" << typeid(T).name() << " destructed\033[0m" | |
<< std::endl; | |
} | |
private: | |
static std::mutex get_stats_mu_; | |
}; | |
template <typename T> | |
std::atomic<size_t> ObjCounter<T>::objects_created(0); | |
template <typename T> | |
std::atomic<size_t> ObjCounter<T>::objects_alive(0); | |
template <typename T> | |
std::mutex ObjCounter<T>::get_stats_mu_; | |
#endif // IROHA_OBJ_COUNTER_HPP |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment