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



我认为在MSVC++中发现了一个错误。或者也许这是我缺乏知识,我错过了代码中的某些内容。我创建了一个自定义分配器:

#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()

如果你仔细看,分配函数在不同的对象上调用,在另一个对象上调用 deallocate((!此外,他们为什么要对空forward_list执行分配?对于其他容器,这也是这样做的。并且在 GCC 上运行良好。我会感谢所有的想法!

编辑

我想指出的是,当我使用 malloc 和 free 时,完全没有问题。但是,如果我的分配器使用自己的内存管理机制,您会发现地址557863137412用于分配的对象在创建用于释放的对象557863137460之前被销毁。这根本行不通。

没有错误。

如果你仔细观察allocate函数在不同的对象上调用,deallocate()在另一个对象上调用!

您打印的是分配器的地址,而不是内存(取消(分配。分配器的副本应该能够释放彼此分配的内存,并且允许实现自由复制分配器。(特别是,在这种情况下,它看起来像是在分配和解除分配之前重新绑定存储的分配器。

此外,他们为什么要对空forward_list进行分配?

只有在调试模式下构建时,您才会看到这一点,该模式(除其他外(激活了他们的迭代器调试机制。该机器需要额外的内存,这些内存在建造集装箱时分配,在销毁集装箱时解除。

相关内容

最新更新