Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- template <class T>
- class shared_ptr {
- public:
- constexpr shared_ptr() : ptr_(nullptr), counter_(nullptr) {}
- shared_ptr(T* ptr) : ptr_(ptr), counter_(new size_t(1)) {}
- shared_ptr(const shared_ptr<T>& r) : ptr_(r.ptr_), counter_(r.counter_) {
- ++*(counter_);
- }
- void reset() {
- --*(counter_);
- if (*counter_ == 0) {
- delete ptr_;
- delete counter_;
- }
- ptr_ = nullptr;
- counter_ = new size_t(0);
- }
- void reset(T* ptr) {
- --*(counter_);
- if (*counter_ == 0) {
- delete ptr_;
- delete counter_;
- }
- ptr_ = ptr;
- counter_ = new size_t(1);
- }
- T* get() const { return ptr_; }
- T& operator*() const { return *ptr_; }
- T* operator->() const { return ptr_; }
- long use_count() const { return *counter_; }
- bool unique() const { return *counter_ == 1; }
- operator bool() const { return ptr_ != nullptr; }
- void swap(shared_ptr& r) {
- T* tmp_ptr = ptr_;
- size_t* tmp_counter = counter_;
- ptr_ = r.ptr_;
- counter_ = r.counter_;
- r.ptr_ = tmp_ptr;
- r.counter_ = tmp_counter;
- }
- ~shared_ptr() {
- --*(counter_);
- if (*counter_ == 0) {
- delete ptr_;
- delete counter_;
- }
- }
- private:
- T* ptr_;
- size_t* counter_;
- };
- class A {
- public:
- A() { std::cout << "A:A()" << std::endl; }
- void method() { std::cout << "A:method()" << std::endl; }
- ~A() { std::cout << "~A:A()" << std::endl; }
- };
- int main() {
- shared_ptr<A> a(new A);
- shared_ptr<A> b(a);
- //shared_ptr<int[5]> A;
- shared_ptr<A> c(b);
- std::cout << a.use_count() << std::endl;
- a.reset(new A);
- std::cout << a.use_count() << std::endl;
- std::cout << b.use_count() << std::endl;
- b.reset();
- std::cout << b.use_count() << std::endl;
- std::cout << c.use_count() << std::endl;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement