dimanche 12 février 2023

The smart pointer from cracking the code interview

struct Data
{
    ~Data()
    {
        std::cout << "dtor" << std::endl;
    }
};

template <typename T> class SmartPointer
{

public:
    SmartPointer(T* ptr)
    {
        ref = ptr;
        ref_count = (unsigned int*)malloc(sizeof(unsigned));
        *ref_count = 1;
    }

    SmartPointer(SmartPointer<T>& sptr)
    {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++(*ref_count);
    }

    SmartPointer<T>& operator=(SmartPointer<T>& sptr)
    {
        if (this == &sptr)
            return *this;

        if (*ref_count > 0)
            remove();

        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++(*ref_count);
        return *this;
    }

    ~SmartPointer()
    {
        remove();
    }

    T getValue()
    {
        return *ref;
    }

private: // protected:
    T* ref = nullptr;
    unsigned* ref_count = nullptr;

    void remove()
    {
        --(*ref_count);
        if (!*ref_count)
        {
            delete ref;
            free (ref_count);
            ref = nullptr;
            ref_count = nullptr;
        }
    }
};

int main()
{
//    Data data;

//    auto data = new Data;
//    delete data;

    auto data = SmartPointer<Data>(new Data);
}

Saw the above implementation of a smart pointer on cracking the code interview 6th ed.

I changed protected members to be private and it still seem to work. Do we really need them do be protected?

Aucun commentaire:

Enregistrer un commentaire