Skip to content

Instantly share code, notes, and snippets.

@icedraco
Created April 30, 2020 23:43
Show Gist options
  • Save icedraco/61393a450c4f945d7caa01fcb0dfb533 to your computer and use it in GitHub Desktop.
Save icedraco/61393a450c4f945d7caa01fcb0dfb533 to your computer and use it in GitHub Desktop.
Custom C++ smart_ptr for the sake of exsercise...
#include <cstdio>
template<typename T>
class smartptr {
public:
smartptr(T* v) : _data(new data(v)) {
printf(" * smartptr: obtained value %d\n", *_data->value);
}
smartptr(const smartptr &other) : _data(other._data) {
_data->refcount++;
printf(" * smartptr: copied pointer for value %d (ref: %lu)\n", **_data, _data->refcount);
}
~smartptr() {
reset();
}
void operator=(const smartptr &other) {
reset();
_data = other._data;
_data->refcount++;
printf(" * smartptr: data reassigned to value %d (ref: %lu)\n", **_data, _data->refcount);
}
T& operator*() {
return **_data;
}
void reset() {
if (_data != nullptr && --_data->refcount == 0) {
printf(" * smartptr: destroying data [%d]\n", **_data);
delete _data->value;
delete _data;
_data = nullptr;
} else if (_data) {
printf(" * smartptr: ref--(%d) -> %ld\n", **_data, _data->refcount);
} else {
printf(" * smartptr: reset(<null>)\n");
}
}
private:
class data {
public:
T* value;
unsigned long refcount = 1;
data(T* v) : value(v) {}
data(const data &other) = delete;
T& operator*() {
return *value;
}
};
data* _data;
};
int main(int argc, char **argv) {
smartptr<int> y(new int(1234));
smartptr<int> z = y;
printf("y: %d\n", *y);
y = smartptr<int>(new int(999));
printf("z: %d\n", *z);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment