Sobes.tech
Junior — Senior

SharedPtr: implementation of the constructor accepting a raw pointer

livecode

Task condition

It is necessary to implement a constructor for the template class that takes a pointer of type T*. The constructor must assign the received pointer to the m_ptr field and initialize the reference counter m_counter with the value 1.


template <class T>
class SharedPtr {
    int* m_counter = nullptr;
    T* m_ptr = nullptr;

public:
    SharedPtr() = default;

    SharedPtr(const SharedPtr& p) {
        m_ptr = p.m_ptr;
        m_counter = p.m_counter;
        (*m_counter)++;
    }

    SharedPtr(T* ptr) {
        m_ptr = ptr;
        m_counter = new int(1);
    }
};