这样做的方法是替换分配器.请注意,vector和string是目前实际检查其分配器max_size的唯一容器.这个想法是,由于这些容器保证元素存储在连续的内存中,容器会向分配器询问分配器可以处理多少元素.
这是个主意
template<class T>
struct MyAllocator:std::allocator<T>
{
template <class U>
struct rebind { typedef MyAllocator<U> other; };
typedef typename std::allocator<T>::size_type size_type;
MyAllocator(size_type sz=1234)
: m_maxsize(sz)
{}
size_type max_size() const { return m_maxsize; }
private:
size_type m_maxsize;
};
Run Code Online (Sandbox Code Playgroud)
然后制作一个新的载体
typedef std::vector<Type,MyAllocator<Type>> vec_t;
vec_t vec(vec_t::allocator_type(4567));
Run Code Online (Sandbox Code Playgroud)
我还没有尝试编译这段代码,但它应该可以工作.