Skip to content

Instantly share code, notes, and snippets.

@ElFeesho
Created May 19, 2016 18:47
Show Gist options
  • Select an option

  • Save ElFeesho/d8805b3f0bce0adeeb68193d04afd40a to your computer and use it in GitHub Desktop.

Select an option

Save ElFeesho/d8805b3f0bce0adeeb68193d04afd40a to your computer and use it in GitHub Desktop.
Rule of 5 and Rule of 0 demonstration
#include <iostream>
#include "refcount.h"
class Foo {
public:
explicit Foo() { }
private:
RefCount<Foo> _ref;
};
using namespace std;
int main() {
{
Foo bar;
Foo newBar(bar);
Foo newBarTwo = bar;
Foo moveBar(std::move(bar));
Foo moveBarTwo = std::move(newBarTwo);
dumpRefCounts();
}
dumpRefCounts();
return 0;
}
#pragma once
#include <iostream>
#include <map>
#include <string>
#include <memory>
static std::map<std::string, int> refCounts;
void incRefCount(const std::string &name)
{
if (refCounts.find(name) == refCounts.end())
{
refCounts[name] = 0;
}
refCounts[name]++;
}
void decRefCount(const std::string &name)
{
if (refCounts.find(name) != refCounts.end())
{
refCounts[name]--;
}
else
{
std::cout << "(moved object dtor)" << std::endl;
}
}
void dumpRefCounts() {
for (auto refTuple : refCounts)
{
std::cout << "References to " << refTuple.first << " - " << refTuple.second << std::endl;
}
}
// Implement rule of 5 to observe rule of 0 operation of other objects
template<typename T>
class RefCount
{
public:
explicit RefCount() : _name{typeid(T).name()} {
incRefCount(_name);
std::cout << _name << " ctor" << std::endl;
};
RefCount(RefCount &copy) {
this->_name = copy._name;
std::cout << _name << " copy" << std::endl;
incRefCount(_name);
}
RefCount(RefCount &&move) {
this->_name = std::string(std::move(move._name));
std::cout << _name << " move" << std::endl;
}
RefCount operator=(RefCount &copy) {
this->_name = copy._name;
std::cout << _name << " copy op" << std::endl;
incRefCount(_name);
return *this;
}
RefCount operator=(RefCount &&move) {
this->_name = std::string(std::move(move._name));
std::cout << _name << " move op" << std::endl;
return *this;
}
~RefCount() {
std::cout << _name << " dtor" << std::endl;
decRefCount(_name);
}
private:
std::string _name;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment