Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #define NOTHING 0
- #define MOVE 1
- #define DEEP_COPY 2
- #define MOVE_RVAL 3
- #define METHOD NOTHING
- class Entity
- {
- int num;
- public:
- Entity(int n = 0) : num{n} { std::cout << "Entity constructed\n";};
- ~Entity() {std::cout << "Entity destructed\n";}
- void print() { std::cout << "Entity = " << num << "\n";};
- };
- class SmartPtr
- {
- Entity* ptr;
- public:
- SmartPtr(Entity* eptr = nullptr) : ptr{eptr} {};
- #if METHOD == MOVE
- SmartPtr(SmartPtr& sPtr);
- SmartPtr& operator=(SmartPtr& sPtr);
- #endif
- #if METHOD == MOVE_RVAL
- SmartPtr(SmartPtr&& sPtr);
- SmartPtr& operator=(SmartPtr&& sPtr);
- #endif
- #if METHOD == DEEP_COPY
- SmartPtr(const SmartPtr& sPtr);
- SmartPtr& operator=(const SmartPtr& sPtr);
- #endif
- Entity& operator*() {return *ptr;};
- Entity* operator->() {return ptr;};
- bool isEmpty() { return ptr == nullptr;};
- ~SmartPtr() { delete ptr; };
- };
- #if METHOD == MOVE
- SmartPtr::SmartPtr(SmartPtr& sPtr) // Move
- : ptr{sPtr.ptr}
- {
- sPtr.ptr = nullptr;
- }
- SmartPtr& SmartPtr::operator =(SmartPtr& sPtr) // Move
- {
- if ( this == &sPtr) { return *this; };
- delete ptr;
- ptr = sPtr.ptr;
- sPtr.ptr = nullptr;
- return *this;
- }
- #endif
- #if METHOD == MOVE_RVAL
- SmartPtr::SmartPtr(SmartPtr&& sPtr) // Move rvalue
- : ptr{sPtr.ptr}
- {
- sPtr.ptr = nullptr;
- }
- SmartPtr& SmartPtr::operator =(SmartPtr&& sPtr) // Move rvalue
- {
- if ( this == &sPtr) { return *this; };
- delete ptr;
- ptr = sPtr.ptr;
- sPtr.ptr = nullptr;
- return *this;
- }
- #endif
- #if METHOD == DEEP_COPY
- SmartPtr::SmartPtr(const SmartPtr& sPtr) // Deep copy
- : ptr{new Entity}
- {
- *ptr = *sPtr.ptr;
- }
- SmartPtr& SmartPtr::operator =(const SmartPtr& sPtr) // Deep copy
- {
- if ( this == &sPtr) { return *this; };
- delete ptr;
- ptr = new Entity;
- *ptr = *sPtr.ptr;
- return *this;
- }
- #endif
- SmartPtr generateEntity()
- {
- SmartPtr sPtr{new Entity{33}};
- return sPtr;
- }
- int main()
- {
- SmartPtr ePtr{new Entity{42}};
- ePtr->print();
- std::cout <<"ePtr.isEmpty: " << ePtr.isEmpty() << '\n';
- #if METHOD == DEEP_COPY || METHOD == MOVE || METHOD == NOTHING
- SmartPtr ePtr1{ePtr};
- ePtr1->print();
- std::cout <<"ePtr.isEmpty: " << ePtr.isEmpty() << '\n';
- #endif
- #if METHOD == MOVE_RVAL
- SmartPtr ePtr1{std::move(ePtr)};
- ePtr1->print();
- std::cout <<"ePtr.isEmpty: " << ePtr.isEmpty() << '\n';
- #endif
- #if METHOD == MOVE || METHOD == DEEP_COPY || METHOD == MOVE_RVAL
- SmartPtr ePtr2 = generateEntity();
- ePtr2->print();
- std::cout <<"ePtr2.isEmpty: " << ePtr2.isEmpty() << '\n';
- #endif
- }
Advertisement
Add Comment
Please, Sign In to add comment