Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #pragma once
- #include <memory>
- #include "Test.h"
- namespace smart_pointer {
- // `exception` class definition
- class exception : std::exception {
- using base_class = std::exception;
- using base_class::base_class;
- };
- // `SmartPointer` class declaration
- template<
- typename T,
- typename Allocator
- >
- class SmartPointer {
- // don't remove this macro
- ENABLE_CLASS_TESTS;
- public:
- using value_type = T;
- SmartPointer(value_type * p = nullptr) {
- core = new Core();
- core->pointer = p;
- if (p != nullptr) {
- core->countpointers = 1;
- }
- }
- // copy constructor
- SmartPointer(const SmartPointer &smart_pointer) {
- core = smart_pointer.core;
- core->countpointers++;
- }
- // move constructor
- SmartPointer(SmartPointer &&smart_pointer) {
- core = smart_pointer.core;
- core->countpointers++;
- smart_pointer.core = nullptr;
- }
- // copy assigment
- SmartPointer &operator=(const SmartPointer &smart_pointer) {
- core = smart_pointer.core;
- core->countpointers++;
- }
- // move assigment
- SmartPointer &operator=(SmartPointer &&smart_pointer) {
- core = smart_pointer.core;
- core->countpointers++;
- smart_pointer.core = nullptr;
- }
- //
- SmartPointer &operator=(value_type * p) {
- core->pointer = p;
- }
- ~SmartPointer() {
- core = nullptr;
- }
- // return reference to the object of class/type T
- // if SmartPointer contains nullptr throw `SmartPointer::exception`
- value_type &operator*() {
- if (core->pointer == nullptr) {
- throw exception();
- }
- return *core->pointer;
- }
- const value_type &operator*() const {
- if (core->pointer == nullptr) {
- throw exception();
- }
- return *core->pointer;
- }
- // return pointer to the object of class/type T
- value_type *operator->() const {
- return core->pointer;
- }
- value_type *get() const {
- if (operator bool()) {
- return core->pointer;
- }
- return nullptr;
- }
- // if pointer == nullptr => return false
- operator bool() const {
- return core->pointer != nullptr;
- }
- // if pointers points to the same address or both null => true
- template<typename U, typename AnotherAllocator>
- bool operator==(const SmartPointer<U, AnotherAllocator> &sm) const {
- return sm.core->pointer == core->pointer;
- }
- // if pointers points to the same address or both null => false
- template<typename U, typename AnotherAllocator>
- bool operator!=(const SmartPointer<U, AnotherAllocator> &sm) const {
- return sm.core->pointer != core->pointer;
- }
- // if smart pointer contains non-nullptr => return count owners
- // if smart pointer contains nullptr => return 0
- std::size_t count_owners() const {
- if (core->pointer == nullptr) {
- return 0;
- }
- return core->countpointers;
- }
- private:
- class Core {
- public:
- size_t countpointers;
- value_type * pointer;
- };
- Core *core;
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement