Skip to content

Instantly share code, notes, and snippets.

@SF-Zhou
Created January 25, 2019 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SF-Zhou/53bc8fe4094fe586f10d40d3f1c750a9 to your computer and use it in GitHub Desktop.
Save SF-Zhou/53bc8fe4094fe586f10d40d3f1c750a9 to your computer and use it in GitHub Desktop.
Simple C++ Shared Ptr
#include <iostream>
template <class T>
class SharedPtr {
public:
SharedPtr(T *rep = nullptr) : rep_(rep), count_ptr_(new int32_t(1)) {}
SharedPtr(const SharedPtr &obj) : count_ptr_(obj.count_ptr_), rep_(obj.rep_) {
increse();
}
SharedPtr &operator=(const SharedPtr &obj) {
rep_ = obj.rep_;
count_ptr_ = obj.count_ptr_;
increse();
return *this;
}
~SharedPtr() {
decrese();
if (count() == 0) {
delete count_ptr_;
delete rep_;
}
}
T *get() const { return rep_; }
operator T *() const { return rep_; }
private:
T *rep_;
int32_t *count_ptr_;
int32_t count() const { return *count_ptr_; }
void increse() { ++(*count_ptr_); }
void decrese() { --(*count_ptr_); }
};
class A {
public:
A() { puts("New"); }
~A() { puts("Delete"); }
};
int main() {
SharedPtr<A> b;
{
SharedPtr<A> a(new A);
b = a;
puts("OK");
}
puts("OK");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment