您可以传递一个自定义分配器,std::basic_string
该分配器具有您想要的最大大小。这应该足够了。也许是这样的:
template <class T>
class my_allocator {
public:
typedef T value_type;
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;
pointer address(reference r) const { return &r; }
const_pointer address(const_reference r) const { return &r; }
my_allocator() throw() {}
template <class U>
my_allocator(const my_allocator<U>&) throw() {}
~my_allocator() throw() {}
pointer allocate(size_type n, void * = 0) {
// fail if we try to allocate too much
if((n * sizeof(T))> max_size()) { throw std::bad_alloc(); }
return static_cast<T *>(::operator new(n * sizeof(T)));
}
void deallocate(pointer p, size_type) {
return ::operator delete(p);
}
void construct(pointer p, const T& val) { new(p) T(val); }
void destroy(pointer p) { p->~T(); }
// max out at about 64k
size_type max_size() const throw() { return 0xffff; }
template <class U>
struct rebind { typedef my_allocator<U> other; };
template <class U>
my_allocator& operator=(const my_allocator<U> &rhs) {
(void)rhs;
return *this;
}
};
然后你可能可以这样做:
typedef std::basic_string<char, std::char_traits<char>, my_allocator<char> > limited_string;
编辑:我刚刚做了一个测试,以确保它按预期工作。以下代码对其进行测试。
int main() {
limited_string s;
s = "AAAA";
s += s;
s += s;
s += s;
s += s;
s += s;
s += s;
s += s; // 512 chars...
s += s;
s += s;
s += s;
s += s;
s += s;
s += s; // 32768 chars...
s += s; // this will throw std::bad_alloc
std::cout << s.max_size() << std::endl;
std::cout << s.size() << std::endl;
}
最后一个s += s
会将它放在顶部并导致std::bad_alloc
异常,(因为我的限制只是短于 64k)。不幸的是 gcc 的std::basic_string::max_size()
实现并不基于你使用的分配器,所以它仍然声称能够分配更多。(我不确定这是否是一个错误......)。
但这肯定会让您以简单的方式对字符串的大小施加硬性限制。您甚至可以将最大大小设为模板参数,这样您只需为分配器编写一次代码。