Created
September 23, 2020 08:52
-
-
Save IMelker/41fac2f2230b16489fdbc42555a193e5 to your computer and use it in GitHub Desktop.
[Cpp] Class counter for object instances by inheritance(gcc)
This file contains hidden or 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
// | |
// 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