lundi 7 juin 2021

Unable to Understand Custom Allocator

I was reading about typedefs vs using on Microsoft docs website: Aliases and typedefs (C++)

#include <stdlib.h>
#include <new>

template <typename T> struct MyAlloc {
    typedef T value_type; // Failed to understand why it is needed

    MyAlloc() { }
    template <typename U> MyAlloc(const MyAlloc<U>&) { } // Failed to understand why it is needed

    bool operator==(const MyAlloc&) const { return true; } // Failed to understand why always true
    bool operator!=(const MyAlloc&) const { return false; } // Failed to understand why always false

    T * allocate(const size_t n) const {
        if (n == 0) {
            return nullptr;
        }

        if (n > static_cast<size_t>(-1) / sizeof(T)) // Failed to understand this operation
        { 
            throw std::bad_array_new_length();
        }

        void * const pv = malloc(n * sizeof(T));

        if (!pv) {
            throw std::bad_alloc();
        }

        return static_cast<T *>(pv);
    }

    void deallocate(T * const p, size_t) const {
        free(p);
    }
};

#include <vector>
using MyIntVector = std::vector<int, MyAlloc<int>>;

#include <iostream>

int main ()
{
    MyIntVector foov = { 1701, 1764, 1664 };

    for (auto a: foov) std::cout << a << " ";
    std::cout << "\n";

    return 0;
}

I am not able to understand this piece of code in many places, as I commented throughout the code. Could someone explain the above code for a person who is at a beginner-to-intermediate level of C++?

Aucun commentaire:

Enregistrer un commentaire