繁体   English   中英

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

[英]Why my code doesn't work with custom allocator?

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

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);
        }
    };
}
Vector<int> v(CustomAllocator<int>());

你被最烦人的解析击中了。 Vector<int> v(CustomAllocator<int>()); 可以解析为变量声明function 声明,语法更喜欢后者。 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.

即使您使用以下选项之一修复了该错误:

// 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>继承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类型参数,然后甚至不需要构造函数 arguments 因为默认构造函数会做正确的事情:

Vector<int, CustomAllocator> v;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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