Skip to content

Instantly share code, notes, and snippets.

@erodactyl
Created November 25, 2017 13:13
Show Gist options
  • Save erodactyl/9977a25bca441057eb3a33d16591e5dd to your computer and use it in GitHub Desktop.
Save erodactyl/9977a25bca441057eb3a33d16591e5dd to your computer and use it in GitHub Desktop.
Automatic reference counting
#include <iostream>
using namespace std;
template <class T>
class Smart {
private:
T* pointee;
int* ref_count;
public:
Smart(T* ptr) : pointee(ptr), ref_count(new int(0)) {
(*ref_count)++;
cout << "number of refs is " << *ref_count << endl;
}
Smart(const Smart<T>& tmp) : pointee(tmp.pointee), ref_count(tmp.ref_count) {
(*ref_count)++;
cout << "number of refs is " << *ref_count << endl;
}
~Smart() {
(*ref_count)--;
if(*ref_count == 0) {
cout << "pointee deleted" << endl;
delete pointee;
delete ref_count;
}
}
T& operator*(){
return *pointee;
}
};
void print(Smart<int> copy) {
cout << *copy << endl;
}
void test_func() {
Smart<int> smart(new int(10));
print(smart);
}
int main() {
test_func();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment