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