Skip to content

Instantly share code, notes, and snippets.

@alekseyl1992
Created September 3, 2016 15:56
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 alekseyl1992/7b3630308277c9b98e0bd15f22b97d54 to your computer and use it in GitHub Desktop.
Save alekseyl1992/7b3630308277c9b98e0bd15f22b97d54 to your computer and use it in GitHub Desktop.
my_shared_ptr_no_heap.cc
#include <iostream>
#include <memory>
#include <string>
#include <vector>
template <typename T>
class my_shared_ptr {
public:
my_shared_ptr(T* raw_ptr)
: raw_ptr_(raw_ptr),
ref_count_value_(1),
ref_count_(&ref_count_value_) {
}
my_shared_ptr(const my_shared_ptr<T>& other)
: raw_ptr_(other.raw_ptr_),
ref_count_(other.ref_count_) {
inc();
}
~my_shared_ptr() {
dec();
}
my_shared_ptr<T>& operator=(const my_shared_ptr<T> other) {
dec();
raw_ptr_ = other.raw_ptr_;
ref_count_ = other.ref_count_;
inc();
return *this;
}
T* operator ->() {
return raw_ptr_;
}
protected:
void inc() {
++*ref_count_;
}
void dec() {
if (*ref_count_ != 0) {
--*ref_count_;
}
if (*ref_count_ == 0) {
delete raw_ptr_;
raw_ptr_ = nullptr;
}
}
private:
T* raw_ptr_ = nullptr;
size_t ref_count_value_;
size_t* ref_count_;
};
class A {
public:
A(const std::string& name)
: name_(name) {
std::cout << "A(" << name_ << ")" << std::endl;
}
~A() {
std::cout << "~A(" << name_ << ")" << std::endl;
}
void some_method() {
std::cout << "some_method(" << name_ << ")" << std::endl;
}
private:
std::string name_;
};
void fun(my_shared_ptr<A> p) {
p->some_method();
}
int main() {
my_shared_ptr<A> a(new A("a"));
my_shared_ptr<A> b(new A("b"));
a = b;
fun(a);
fun(b);
my_shared_ptr<A> c(a);
std::vector<my_shared_ptr<A>> vec = {
a, b, a, b,
my_shared_ptr<A>(new A("c"))
};
for (auto p : vec) {
p->some_method();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment