Skip to content

Instantly share code, notes, and snippets.

@EarlGray
Last active January 1, 2016 13:19
Show Gist options
  • Save EarlGray/8150013 to your computer and use it in GitHub Desktop.
Save EarlGray/8150013 to your computer and use it in GitHub Desktop.
C++ overloading
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
template <typename T>
class clever_ptr {
string log;
struct pointed {
T* ptr;
int nref;
pointed(T* pt): ptr(pt), nref(1) {}
} *me;
void release() {
cout << log << "dropped" << endl;
if (-- me->nref == 0) {
cout << log << "deleted!" << endl;
delete me->ptr;
delete me;
}
}
void acquire(pointed *pthat) {
cout << log << "shared" << endl;
this->me = pthat;
++ me->nref;
}
public:
clever_ptr(T * pt) {
log = string("clever_ptr<") + T::name + ">: ";
cout << log << "initialized" << endl;
me = new pointed(pt);
}
clever_ptr(clever_ptr<T> &that) {
log = string("clever_ptr<") + T::name + ">: ";
acquire(that.me);
}
clever_ptr<T> operator=(clever_ptr<T> &that) {
release();
acquire(that.me);
}
T& operator *() {
return *me->ptr;
}
T* operator->() {
return me->ptr;
}
~clever_ptr() {
release();
}
};
struct GuineaPig {
const static string name;
int legs;
int tails;
GuineaPig(): legs(4), tails(1) {}
void utter_sound() {
cout << "I have " << legs << " legs" << endl;
}
};
const string GuineaPig::name = "GuineaPig";
int main() {
clever_ptr<GuineaPig> *gp = new clever_ptr<GuineaPig>(new GuineaPig());
cout << "First reference created!" << endl;
clever_ptr<GuineaPig> pgp2 = *gp;
cout << "Second reference created" << endl;
delete gp;
cout << "First reference dropped" << endl;
++ pgp2->legs;
pgp2->utter_sound();
}
#include <iostream>
using std::cout;
using std::endl;
struct MarsBomber {
int accessToThisFieldLaunchesMissilesToMars;
};
class GiuneaPig {
int count;
MarsBomber bomber;
public:
GiuneaPig(): count(0) {
bomber.accessToThisFieldLaunchesMissilesToMars = 5;
};
void operator()() {
std::cout << "called: " << count << std::endl;
}
int* operator*() {
return &count;
}
operator int() {
return count;
}
GiuneaPig& operator=(int val) {
count = val;
return *this;
}
int operator++() {
cout << "preincrement" << endl;
return ++count;
}
int operator++(int) {
cout << "postincrement" << endl;
int c = count;
++count;
return c;
}
MarsBomber* operator->() {
cout << "Missiles to Mars launched" << endl;
return &bomber;
}
};
int main() {
GiuneaPig guineaPig;
guineaPig = 4;
guineaPig();
cout << guineaPig + 1 << endl;
guineaPig++;
++guineaPig;
cout << *guineaPig << endl;
cout << guineaPig->accessToThisFieldLaunchesMissilesToMars << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment