Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include <chrono>
- class Element
- {
- int val;
- //std::shared_ptr<Element> pair;
- public:
- Element(int valP) : val{ valP }, pair{nullptr} { std::cout << "Element constructed for " << this << '\n'; };
- Element() : Element{ 0 } {};
- ~Element(){ std::cout << "Element destructed for " << this << '\n'; };
- int getVal() const { return val; };
- //friend bool addPair(std::shared_ptr<Element>& lhs, std::shared_ptr<Element>& rhs)
- //{
- // if (!lhs or !rhs)
- // {
- // return false;
- // };
- // lhs->pair = rhs;
- // rhs->pair = lhs;
- // std::cout << lhs->getVal() << " paired with " << rhs->getVal() << '\n';
- // return true;
- //}
- };
- template <typename T>
- class SmartPtr
- {
- T* ptr;
- //int* countPtr;
- public:
- SmartPtr(T* ptrP) : ptr{ ptrP } {}
- ~SmartPtr() { delete ptr; }
- SmartPtr(const SmartPtr& obj) = delete;
- SmartPtr& operator=(const SmartPtr& obj) = delete;
- SmartPtr(SmartPtr&& sPtr)
- : ptr{ sPtr.ptr }
- {
- sPtr.ptr = nullptr;
- }
- SmartPtr& operator=(SmartPtr&& sPtr)
- {
- if (!(&sPtr == this))
- {
- ptr = sPtr.ptr;
- sPtr.ptr = nullptr;
- }
- return *this;
- }
- T& operator*() { return *ptr; };
- const T& operator*()const { return *ptr; };
- T* operator->() { return ptr; };
- const T* operator->()const { return ptr; };
- T* release() noexcept { ptr = nullptr; return ptr; };
- const T* get()const { return ptr; };
- };
- void foo()
- {
- //Element* ptr{ new Element{rand() % 10} };
- //SmartPtr<Element> sPtr{ ptr };
- SmartPtr<Element> sPtr{ new Element{rand() % 10} };
- std::cout << "Value is: " << sPtr->getVal() << '\n';
- //if (ptr->getVal() < 6) { throw std::runtime_error("Too small"); };
- if (sPtr->getVal() < 6) { throw std::runtime_error("Too small"); };
- // some work with ptr
- //delete ptr;
- }
- std::unique_ptr<Element> generateElement()
- {
- auto ptr{ std::make_unique<Element>(rand() % 10) };
- return ptr;
- }
- void useElement(const Element& el)
- {
- std::cout << "useElement: Value is: " << el.getVal() << '\n';
- //return el;
- }
- void useShared(std::shared_ptr<Element> ptr)
- {
- std::cout << "useShared " << ptr->getVal() << '\n';
- }
- int main()
- {
- srand(time(nullptr));
- std::shared_ptr<Element> sPtrTwo;
- // sPtrOne
- {
- //Element* elPtr{ new Element{333} };
- std::shared_ptr<Element> sPtrOne{ std::make_shared<Element>(42) };
- std::shared_ptr<Element> newHier{ std::make_shared<Element>(33) };
- auto newhierOne{ newHier };
- std::cout << "sPtrOne " << sPtrOne->getVal() << '\n';
- sPtrTwo = sPtrOne;
- }
- useShared(sPtrTwo);
- // sPtrThree
- {
- auto sPtrThree{ sPtrTwo };
- std::cout << "sPtrThree " << sPtrThree->getVal() << '\n';
- }
- std::cout << "sPtrTwo " << sPtrTwo->getVal() << '\n';
- }
Advertisement
Add Comment
Please, Sign In to add comment