Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- template<typename T>
- class SharedPtr {
- private:
- T* ptr;
- size_t* ref_c;
- public:
- SharedPtr() : ptr(nullptr), ref_c(new size_t(1)) {}
- SharedPtr(T* p) : ptr(p), ref_c(new size_t(1)) {}
- SharedPtr(const SharedPtr& other) : ptr(other.ptr), ref_c() {
- ref_c = other.ref_c;
- ++(*ref_c);
- }
- void swap(SharedPtr& other) {
- std::swap(ptr, other.ptr);
- std::swap(ref_c, other.ref_c);
- }
- SharedPtr(SharedPtr&& other) {
- this->swap(other);
- }
- void reset(T* p) {
- --(*ref_c);
- ref_c = new size_t(1);
- ptr = p;
- }
- SharedPtr& operator =(T* p) {
- this->reset(p);
- return (*this);
- }
- SharedPtr& operator =(const SharedPtr& other) {
- --(*ref_c);
- ptr = other.ptr;
- ref_c = other.ref_c;
- ++(*ref_c);
- return (*this);
- }
- SharedPtr& operator =(SharedPtr&& other) {
- this->swap(other);
- return (*this);
- }
- const T& operator *() const {
- return *ptr;
- }
- T& operator *() {
- return *ptr;
- }
- T* operator ->() const {
- return ptr;
- }
- T* get() const {
- return ptr;
- }
- explicit operator bool() const {
- return ptr == nullptr;
- }
- ~SharedPtr() {
- if (ref_c != nullptr && *ref_c <= 1) {
- delete ptr;
- delete ref_c;
- } else {
- if (ref_c != nullptr) {
- --(*ref_c);
- }
- }
- }
- };
- using namespace std;
- int main()
- {
- SharedPtr<int> x(new int(6));
- SharedPtr<int> y(std::move(x));
- cout << *y << endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement