Skip to content

Instantly share code, notes, and snippets.

@bombela
Created September 9, 2011 22:18
Show Gist options
  • Save bombela/1207478 to your computer and use it in GitHub Desktop.
Save bombela/1207478 to your computer and use it in GitHub Desktop.
class Speaker
{
public:
struct Scope
{
Scope(bool verbose = false) { resetCounters(); setVerbose(verbose); }
~Scope() { printStats(); }
};
~Speaker() { speak() << "destructor" << std::endl; ++_counters.dtor; }
Speaker(): _id(getNextId())
{ speak() << "constructor" << std::endl; ++_counters.ctor; }
Speaker(const Speaker& from): _id(getNextId())
{ speak() << "copy constructor from " << from.getName() << std::endl; ++_counters.cctor; }
Speaker& operator=(const Speaker& from)
{ speak() << "affectation from " << from.getName() << std::endl; ++_counters.aff; return *this; }
Speaker(Speaker&& from): _id(getNextId())
{ speak() << "move constructor from " << from.getName() << std::endl; ++_counters.mcctor; }
Speaker& operator=(Speaker&& from)
{
speak() << "move affectation from " << from.getName() << std::endl;
++_counters.maff;
return *this;
}
std::ostream& speak(std::ostream& os = std::cout) const
{
if (_counters.verbose)
{
os << getName() << ": ";
return std::cout;
}
static struct PlaceHolder: public std::ostream { } placeHolder;
return placeHolder;
}
friend std::ostream& operator<<(std::ostream& os, const Speaker& spkr)
{
std::ostream::sentry init(os);
if (init)
os << spkr.getName();
return os;
}
static void resetCounters()
{
bool verbose = _counters.verbose;
_counters = SpeakerCounters();
_counters.verbose = verbose;
}
static void setVerbose(bool verbose = true) { _counters.verbose = verbose; }
static std::ostream& printStats(std::ostream& os = std::cout)
{
os << "SpeakerCnters"
<< " dtor=" << _counters.dtor
<< " ctor=" << _counters.ctor
<< " cctor=" << _counters.cctor
<< " mcctor=" << _counters.mcctor
<< " aff=" << _counters.aff
<< " maff=" << _counters.maff
<< std::endl;
return os;
}
private:
static struct SpeakerCounters
{
unsigned nextId; // uniq id
unsigned dtor; // destructor
unsigned ctor; // constructor
unsigned cctor; // copy constructor
unsigned mcctor; // move constructor
unsigned aff; // affection
unsigned maff; // move affection
bool verbose;
SpeakerCounters():
nextId(0),
dtor(0),
ctor(0),
cctor(0),
mcctor(0),
aff(0),
maff(0),
verbose(false)
{}
} _counters;
unsigned _id;
unsigned getNextId() const { return _counters.nextId++; }
std::string getName() const
{
std::ostringstream os;
os << "Speaker" << _id;
return os.str();
}
};
Speaker::SpeakerCounters Speaker::_counters;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment