为什么我的代码不适用于自定义分配器?

问题描述 投票:1回答:1

是什么问题,以及如何解决?无需尝试挤压自定义分配器,乍一看,我的向量即可正常工作。我也很乐意指出我的代码中的任何错误。或正确实现自定义矢量或其他容器的示例,这对我有帮助。此代码无效:

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实现(应该可以):

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);
        }
    }
};

矢量实现:

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);
        }
    };
}
c++ allocator
1个回答
3
投票
Vector<int> v(CustomAllocator<int>());

您被most vexing parse击中。可以将Vector<int> v(CustomAllocator<int>());解析为变量声明函数声明,语法更喜欢后者。因此,编译器认为v是一个函数,这就是为什么您收到“表达式必须具有类类型”错误的原因-您只能对具有类类型的值调用方法,而v是一个函数。 >

即使您使用以下选项之一解决了该错误:

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

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

您的代码仍然无法实现您期望的效果,尽管它可以运行。

Vector<int>Vector<int, std::allocator>是同一件事,因此v仍将使用标准分配器。

为什么这不会导致编译错误?因为CustomAllocator<int> inherits

std::allocator<int>(不应该这样!),所以std::allocator<int>复制构造函数用于将您的自定义分配器切成std::allocator<int>,然后程序使用标准分配器进行处理。您的CustomAllocator<int>临时目录基本上已转换为std::allocator<int>

为了说明,以上两个“固定”示例都大致

等效于此代码(如果我们忽略了一些与程序的可观察行为无关的有价复制/移动):
// 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);

正确的解决方法是指定第二个Vector类型参数,然后甚至不需要构造函数参数,因为默认构造函数将做正确的事情:

Vector<int, CustomAllocator> v;
© www.soinside.com 2019 - 2024. All rights reserved.