启用MSVC调试迭代器时堆栈分配器访问冲突

问题描述:

我制作了一个简单的堆栈分配器,可用于在堆栈上分配小容器。 我一直在使用这个类一段时间,它一直工作正常。 但是,今天我又切换了调试迭代器(_ITERATOR_DEBUG_LEVEL=2),并且在由此开关激活的调试代码中突然出现访问冲突。启用MSVC调试迭代器时堆栈分配器访问冲突

模板编程和标准库编码约定的混合使得这非常难以调试,而且我也不完全是分配器方面的专家。我违反了分配器的某种规则吗?

下面的代码应该能够重现错误。

#include <memory> 
#include <vector> 

template <typename T, size_t N, template <typename> typename Allocator = std::allocator> 
class StackAllocator : public Allocator<T> 
{ 
    public: 
    using base   = Allocator<T>; 
    using pointer_type = typename base::pointer; 
    using size_type = typename base::size_type; 

    StackAllocator() noexcept = default; 
    StackAllocator(const StackAllocator& a_StackAllocator) noexcept = default; 

    template <typename U> 
    StackAllocator(const StackAllocator<U, N, Allocator>& a_StackAllocator) noexcept 
    { 
    } 

    pointer_type allocate(size_type a_Size, void* a_Hint = nullptr) 
    { 
     if (!m_Active && a_Size <= N) 
     { 
      m_Active = true; 
      return GetStackPointer(); 
     } 
     else 
     { 
      return base::allocate(a_Size, a_Hint); 
     } 
    } 

    void deallocate(pointer_type a_Pointer, size_type a_Size) 
    { 
     if (a_Pointer == GetStackPointer()) 
     { 
      m_Active = false; 
     } 
     else 
     { 
      base::deallocate(a_Pointer, a_Size); 
     } 
    } 

    template <class U> 
    struct rebind 
    { 
     using other = StackAllocator<U, N, Allocator>; 
    }; 

    private: 
    pointer_type GetStackPointer() 
    { 
     return reinterpret_cast<pointer_type>(m_Data); 
    } 

    std::aligned_storage_t<sizeof(T), alignof(T)> m_Data[N]; 
    bool m_Active = false; 
}; 

template <typename T, size_t N> 
class StackVector : public std::vector<T, StackAllocator<T, N>> 
{ 
    public: 
    using allocator_type = StackAllocator<T, N>; 
    using base   = std::vector<T, allocator_type>; 

    StackVector() noexcept(noexcept(allocator_type())): 
     StackVector(allocator_type()) 
    { 
    } 

    explicit StackVector(const allocator_type& a_Allocator) noexcept(noexcept(base(a_Allocator))): 
     base(a_Allocator) 
    { 
     base::reserve(N); 
    } 

    using base::vector; 
}; 

int main(int argc, char* argv[]) 
{ 
    StackVector<size_t, 1> v; 

    return v.capacity(); 
} 

我正在使用MSVC 2017(15.4.0)。

+3

该标准要求从分配器'a'构造的分配器'b'拷贝 - 等于'a';这又意味着'a'分配的内存可以被'b'解除分配。你的班级违反了这个要求,因此不是一个有效的分配器。实际上,你继承了'std :: allocator :: operator ==',它总是返回'true';但是你的班级实例是非常不可互换的。 –

+1

原来的答案是downvoted,但主要的一点是你不能在分配器中存储,因为它们是无状态的类价值类型。我什至不知道你会如何支持相同类型的多个这样的分配器。另外,您必须努力确保分配仍在使用中时存储不会超出范围。例如。在存储被破坏之前调用断言释放。 –

这个问题确实违反了@Igor所说的要求。我通过在分配器之外存储堆栈数据解决了这个问题。现在,StackVector是数据的所有者,分配器及其副本都指向该内存,从而确保由一个分配器分配的内存可以由该分配器的副本释放。

该解决方案确实会给用户带来一点复杂性(现在必须管理2个对象而不是1个),但在分配器需求内部似乎没有其他方法,并且可以通过包装容器也是如此。

该解决方案的一个很好的例子可以在Chromium's StackAllocator中找到。