当我尝试这个时:
#include <functional>
#include <iostream>
#include <memory>
#include <set>
template<class T>
struct MyAlloc
{
typedef std::allocator<T> Base;
typedef typename Base::value_type value_type;
typedef typename Base::pointer pointer;
typedef typename Base::const_pointer const_pointer;
typedef typename Base::reference reference;
typedef typename Base::const_reference const_reference;
typedef typename Base::size_type size_type;
typedef typename Base::difference_type difference_type;
Base a;
MyAlloc() { }
template<class U> MyAlloc(MyAlloc<U> const &) { }
template<class U> struct rebind { typedef MyAlloc<U> other; };
pointer allocate(size_type n, void const * = NULL)
{
std::cout << "Allocating " << n << " objects" << std::endl;
return this->a.allocate(n);
}
void deallocate(pointer p, size_type n) { return this->a.deallocate(p, n); }
};
int main(int argc, char *argv[])
{
std::set<int, std::less<int>, MyAlloc<int> > set;
}
我明白了Allocating 1 objects
。
但我不明白——为什么这个堆分配是必要的?堆栈内存足以默认构建其他容器(如) ,std::vector
那么为什么需要堆分配呢?set
map