Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- template<class T>
- struct ControlBlock {
- size_t shared_count;
- size_t weak_count;
- T* object;
- template<class ... Args>
- ControlBlock(size_t count, Args&& ... args) {
- };
- };
- template<class T>
- class Shared_Ptr {
- T* ptr = nullptr;
- size_t* count = nullptr;
- ControlBlock<T>* cptr = nullptr;
- template<class U, class ... Args>
- friend Shared_Ptr<U> Make_Shared(Args&& ... args);
- Shared_Ptr(ControlBlock<T>* ptr) : cptr(ptr), ptr(ptr->object)
- {
- }
- public:
- Shared_Ptr()
- {
- }
- explicit Shared_Ptr(T* ptr) : ptr(ptr), count(new int(1))
- {
- }
- size_t use_count() const noexept;
- T* get() const noexept;
- ~Shared_Ptr()
- {
- if (!cptr) return;
- --cptr->shared_count;
- if (cptr->shared_count == 0)
- {
- delete ptr;
- if (cptr->weak_count == 0)
- {
- delete cptr;
- }
- }
- }
- };
- template <class T, class ... Args>
- Shared_Ptr<T> Make_Shared(Args&& ... args)
- {
- auto p = new ControlBlock<T>(1, std::forward<Args>(args)...);
- return Shared_Ptr;
- }
- template<class T>
- class Weak_Ptr {
- private:
- ControlBlock<T>* cptr = nullptr;
- public:
- Weak_Ptr(const Shared_Ptr<T>& p) : cptr(p.cptr)
- {
- }
- bool expired() const
- {
- return cptr->shared_count == 0;
- }
- Shared_Ptr<T> lock() const {
- return Shared_Ptr<T>(cptr);
- }
- ~Weak_Ptr()
- {
- if (!cptr)return;
- --cptr->weak_count;
- if (cptr->weak_count == 0 && cptr->shared_count == 0)
- {
- delete cptr;
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement