代码之家  ›  专栏  ›  技术社区  ›  no one special

MSVC中的C++自定义STL分配器错误?

  •  2
  • no one special  · 技术社区  · 7 年前

    我想在MSVC++中发现了一个bug。或者这可能是我缺乏知识,我错过了一些代码。我创建了一个自定义分配器:

    #include <forward_list>
    #include <iostream>
    
    template <class T>
    class Allocator
    {
        public:
    
            typedef std::size_t size_type;
            typedef std::ptrdiff_t difference_type;
            typedef T *pointer;
            typedef const T *const_pointer;
            typedef T &reference;
            typedef const T &const_reference;
            typedef T value_type;
    
            template <class U>
            struct rebind
            {
                typedef Allocator<U> other;
            };
    
            Allocator()
            {
                std::cout << (ptrdiff_t) this << " Allocator()" << std::endl;
            }
    
            Allocator(const Allocator &allocator)
            {
                std::cout << (ptrdiff_t) this << " Allocator(const Allocator &allocator)" << std::endl;
            }
    
            template <class U>
            Allocator(const Allocator<U> &other)
            {
                std::cout << (ptrdiff_t) this << " Allocator(const Allocator<U> &other)" << std::endl;
            }
    
            ~Allocator()
            {
                std::cout << (ptrdiff_t) this << " ~Allocator()" << std::endl;
            }
    
            pointer allocate(size_type n, std::allocator<void>::const_pointer hint = 0)
            {
                std::cout << (ptrdiff_t) this << " allocate()" << std::endl;
                return (pointer) std::malloc(n * sizeof(T));
            }
    
            void deallocate(pointer p, size_type n)
            {
                std::cout << (ptrdiff_t) this << " deallocate()" << std::endl;
                std::free(p);
            }
    
            void construct(pointer p, const_reference val)
            {
                new (p) T(val);
            }
    
            void destroy(pointer p)
            {
                p->~T();
            }
    };
    

    Allocator<int> allocator;
    std::forward_list<int, Allocator<int>> memoryPoolList(allocator);
    

    我得到了一个输出

    557863138612 Allocator()
    557863138648 Allocator(const Allocator<U> &other)
    557863137412 Allocator(const Allocator<U> &other)
    557863137412 allocate()
    557863137412 ~Allocator()
    557863137460 Allocator(const Allocator<U> &other)
    557863137460 deallocate()
    557863137460 ~Allocator()
    557863138648 ~Allocator()
    557863138612 ~Allocator()
    

    仔细看,allocate函数在不同的对象上调用,deallocate()在另一个对象上调用!此外,他们为什么在空的forward\u列表上执行分配?其他容器也是这样。在GCC上工作得很好。我会感谢所有的想法!

    编辑

    1 回复  |  直到 7 年前
        1
  •  5
  •   T.C. Yksisarvinen    7 年前

    没有bug。

    allocate 函数在不同的对象上调用,并且 deallocate() 另一个!

    此外,他们为什么要在空服务器上执行分配 forward_list

    只有在调试模式下构建时才会看到这一点,而调试模式(除其他外)会激活迭代器调试机制。该机器需要额外的内存,这些内存在容器构造时分配,在容器销毁时释放。