Created
April 30, 2020 23:43
-
-
Save icedraco/61393a450c4f945d7caa01fcb0dfb533 to your computer and use it in GitHub Desktop.
Custom C++ smart_ptr for the sake of exsercise...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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