Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[Cpp] Class counter for object instances by inheritance(gcc)
//
// Created by imelker on 23.09.2020.
//
#ifndef OBJECTCOUNTER_H_
#define OBJECTCOUNTER_H_
#include <cstdio>
#define USE_COUNTER
template<typename T>
class Counter {
public:
Counter() { std::printf("Create %s = 0\n", __PRETTY_FUNCTION__); }
~Counter() { std::printf("Current %s = %u\n", __PRETTY_FUNCTION__, this->_counter); }
Counter& operator++() { std::printf("%s = %u\n", __PRETTY_FUNCTION__, ++this->_counter); return *this; };
Counter& operator--() { std::printf("%s = %u\n", __PRETTY_FUNCTION__, --this->_counter); return *this; };
// delete invalid ussage
Counter(const Counter& other) = delete;
Counter(Counter&& other) = delete;
Counter& operator=(const Counter& other) = delete;
Counter& operator=(Counter&& other) noexcept = delete;
Counter operator++(int) = delete;
Counter operator--(int) = delete;
private:
unsigned int _counter = 0;
};
template<typename T>
class ObjectCounter {
#ifdef USE_COUNTER
public:
ObjectCounter() { ++this->_counter; }
~ObjectCounter() { --this->_counter; }
ObjectCounter(const ObjectCounter&) { ++this->_counter; }
ObjectCounter(ObjectCounter&&) noexcept { ++this->_counter; }
ObjectCounter& operator=(const ObjectCounter& other) { return *this; }
ObjectCounter& operator=(ObjectCounter&& other) noexcept { return *this; }
private:
static Counter<T> _counter;
#endif // USE_COUNTER
};
#ifdef USE_COUNTER
template<typename T>
Counter<T> ObjectCounter<T>::_counter{};
#endif // USE_COUNTER
#endif //OBJECTCOUNTER_H_
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment