Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.