Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace stepik
- {
- template <typename T>
- class shared_ptr
- {
- template <typename U>
- friend class shared_ptr;
- public:
- explicit shared_ptr(T *ptr = nullptr) {
- ptr_ = ptr;
- if (ptr_) {
- count_ = new int(1);
- } else {
- count_ = 0;
- }
- }
- ~shared_ptr()
- {
- decrement_counter();
- }
- template <typename U>
- shared_ptr(const shared_ptr<U> & other)
- {
- ptr_ = other.ptr_;
- count_ = other.count_;
- if (ptr_) {
- ++(*count_);
- }
- }
- template <typename U>
- shared_ptr& operator=(const shared_ptr<U> & other)
- {
- if (this != &other) {
- decrement_counter();
- ptr_ = other.ptr_;
- count_ = other.count_;
- if (other.ptr_) {
- ++(*count_);
- }
- }
- return *this;
- }
- void decrement_counter() {
- if (count_ && ptr_ && !--(*count_)) {
- delete ptr_;
- delete count_;
- count_ = 0;
- }
- }
- explicit operator bool() const
- {
- return (ptr_ != nullptr);
- }
- T* get() const
- {
- return ptr_;
- }
- long use_count() const
- {
- return (count_ ? *count_ : 0);
- }
- T& operator*() const
- {
- return *ptr_;
- }
- T* operator->() const
- {
- return ptr_;
- }
- void swap(shared_ptr& x) noexcept
- {
- std::swap(ptr_, x.ptr_);
- std::swap(count_, x.count_);
- }
- void reset(T *ptr = 0)
- {
- if (ptr_ != ptr) {
- decrement_counter();
- ptr_ = ptr;
- if (ptr) {
- count_ = new int(0);
- if (ptr_) {
- ++(*count_);
- }
- }
- }
- }
- private:
- T* ptr_;
- int* count_;
- };
- } // namespace stepik
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement