简体   繁体   中英

Why my code doesn't work with custom allocator?

What is the problem and how to fix it? Without trying to squeeze a custom allocator, my vector, at first glance, works correctly. I will also be happy to point out any mistakes in my code. Or an example of the correct implementation of a custom vector or another container, that would help me. This code doesn't work:

using MyLib::Vector;
int main()
{
    //Vector<int> v;    //Works fine
    Vector<int> v(CustomAllocator<int>());
    for (size_t i = 0; i < 256; i++) {
        v.push_back(i);    //Error: "expression must have class type"
    }

}

CustomAllocator implementation (it should be fine):

template <typename T>
class CustomAllocator : public std::allocator<T>
{
private:
    using Base = std::allocator<T>;

public:
    T* allocate(size_t count){
        std::cout << ">> Allocating " << count << " elements" << std::endl;
        return Base::allocate(count);
    }

    T* allocate(size_t count, const void* p)
    {
        std::cout << ">> Allocating " << count << " elements" << std::endl;
        return Base::allocate(count, p);
    }

    void deallocate(T* p, size_t count)
    {
        if (p != nullptr)
        {
            std::cout << ">> Deallocating " << count << " elements" << std::endl;
            Base::deallocate(p, count);
        }
    }
};

Vector implementation:

namespace MyLib
{
    template <typename T,
        template <typename Y> class Allocator = std::allocator>
    class Vector
    {
    private:
        std::size_t capacityV;
        std::size_t sizeV;
        Allocator<T> alloc;
        T* arr;

    public:
        typedef Allocator<T> AllocatorType;
        typedef Vector<T, Allocator> VectorType;
        using AllocTraits = std::allocator_traits<Allocator<T>>;

    public:
        explicit Vector(const AllocatorType& allocator = AllocatorType()) {
            capacityV = 0;
            sizeV = 0;
            alloc = allocator;  
            arr = nullptr;
        }
        Vector(const std::initializer_list<T>& values,
            const AllocatorType& allocator = AllocatorType()) {
            sizeV = values.size();
            alloc = allocator;

            if (sizeV < 128)
                capacityV = 128;
            else
                capacityV = (sizeV / 128) * 256;    //that makes sense

            arr = AllocTraits::allocate(alloc, capacityV);
            AllocTraits::construct(alloc, arr, capacityV);
            std::copy(values.begin(), values.end(), arr);
        }
        ~Vector() {
            if (arr)
                AllocTraits::deallocate(alloc, arr, capacityV);
        }

        Vector(const Vector& rhs) {
            capacityV = rhs.capacityV;
            sizeV = rhs.sizeV;
            arr = AllocTraits::allocate(alloc, capacityV);
            std::copy(rhs.arr, rhs.arr + rhs.sizeV, arr);
        }
        Vector(Vector&& rhs) noexcept {
            capacityV = std::move(rhs.capacityV);
            sizeV = std::move(rhs.sizeV);
            arr = std::move(rhs.arr);
        }

        Vector& operator = (const Vector& rhs) {
            capacityV = rhs.capacityV;
            sizeV = rhs.sizeV;
            arr = AllocTraits::allocate(alloc, capacityV);
            std::copy(rhs.arr, rhs.arr + rhs.sizeV, arr);
        }
        Vector& operator = (Vector&& rhs) {
            capacityV = std::move(rhs.capacityV);
            sizeV = std::move(rhs.sizeV);
            arr = std::move(rhs.arr);
        }

        T& operator [](std::size_t i) noexcept {
            if (i < sizeV)
                return arr[i];
            else
                throw std::out_of_range("Wrong index!");
        }
        const T& operator [](std::size_t i) const noexcept {
            if (i < sizeV)
                return arr[i];
            else
                throw std::out_of_range("Wrong index!");
        }

        T* data() noexcept {
            return arr;
        }
        const T* data() const noexcept {
            return arr;
        }

        void push_back(const T& value) {
            ++sizeV;
            if (!arr) {
                if (!capacityV)
                    capacityV = 128;
                arr = AllocTraits::allocate(alloc, capacityV);
            }
            if (sizeV > capacityV) {
                if(capacityV > UINT32_MAX - 256)
                    throw std::runtime_error("Vector overflowed!");
                size_t tmpCap = capacityV;
                capacityV = (sizeV / 128) * 256;    //Увеличим capacityV

                T* buf = AllocTraits::allocate(alloc, capacityV);
                std::move(arr, arr + sizeV - 1, buf);
                AllocTraits::deallocate(alloc, arr, capacityV); //sizeof
                arr = buf;
            }
            arr[sizeV - 1] = value;
        }
        void push_back(T&& value) {
            ++sizeV;
            if (!arr) {
                if (!capacityV)
                    capacityV = 128;
                arr = AllocTraits::allocate(alloc, capacityV);
            }
            if (sizeV > capacityV) {
                if (capacityV > UINT32_MAX - 256)
                    throw std::runtime_error("Vector overflowed!");
                size_t tmpCap = capacityV;
                capacityV = (sizeV / 128) * 256;    //Увеличим capacityV

                T* buf = AllocTraits::allocate(alloc, capacityV);
                std::move(arr, arr + sizeV - 1, buf);
                AllocTraits::deallocate(alloc, arr, capacityV); //sizeof
                arr = buf;
            }
            arr[sizeV - 1] = std::move(value);
        }

        void pop_back() {
            --sizeV;
        }

        void resize(std::size_t size) {
            if (this->sizeV == size)
                return;

            if (this->sizeV > size) {
                this->sizeV = size;
            }
            else {
                size_t tmpSize = size;
                if (capacityV >= size) {
                    this->sizeV = size;
                    for (size_t i = tmpSize - 1; i < this->sizeV; i++)
                        arr[i] = 0;
                }
                else {
                    size_t tmpCap = capacityV;
                    capacityV = (size / 128) * 256; //that makes sense

                    T* buf = AllocTraits::allocate(alloc, capacityV);
                    std::move(arr, arr + sizeV - 1, buf);
                    AllocTraits::deallocate(alloc, arr, capacityV); //sizeof
                    arr = buf;

                    this->sizeV = size;
                    for (size_t i = tmpSize - 1; i < this->sizeV; i++)
                        arr[i] = 0;
                }
            }
        }
        void reserve(std::size_t capacity) {
            if (capacity > this->capacityV)
            {
                size_t tmpCap = capacity;
                this->capacityV = capacity;

                T* buf = AllocTraits::allocate(alloc, capacityV);
                std::move(arr, arr + sizeV - 1, buf);
                AllocTraits::deallocate(alloc, arr, capacityV); //sizeof
                arr = buf;
            }
        }

        std::size_t size() const noexcept {
            return sizeV;
        }
        std::size_t capacity() const noexcept {
            return capacityV;
        }
        bool empty() const noexcept {
            return (sizeV == 0);
        }
    };
}
Vector<int> v(CustomAllocator<int>());

You got hit by the most vexing parse . Vector<int> v(CustomAllocator<int>()); can be parsed as a variable declaration or a function declaration and the grammar prefers the latter. Therefore, the compiler thinks that v is a function and this it why you get the "expression must have class type" error -- you can only invoke methods on values with a class type, but v is a function.

Even if you fixed that error using one of these options:

// C++03 solution (extra parens)
Vector<int> v((CustomAllocator<int>()));

// C++11 solution (uniform initialization)
Vector<int> v{CustomAllocator<int>{}};

Your code still wouldn't do what you expected, though it would run. Vector<int> is the same thing as Vector<int, std::allocator> and so v will still use the standard allocator.

Why doesn't this cause a compilation error? Because CustomAllocator<int> inherits std::allocator<int> (which it shouldn't,), so the std::allocator<int> copy constructor is used to slice your custom allocator into an std::allocator<int> and then the program proceeds using the standard allocator. Your CustomAllocator<int> temporary is basically converted into an std::allocator<int> .

To illustrate, both of the above "fixed" examples are roughly equivalent to this code (if we disregard some value copies/moves that are irrelevant to the program's observable behavior):

// Creates a custom allocator value.
CustomAllocator<int> a;

// Custom allocator is converted to std::allocator<int>.
std::allocator<int> b(a);

// std::allocator<int> is provided to the Vector constructor.
Vector<int> v(b);

The correct fix is to specify the second Vector type parameter and then the constructor arguments aren't even needed since the default constructor will do the right thing:

Vector<int, CustomAllocator> v;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM