我正在使用一个低级API,它接受一个char *和数值来分别表示一个字符串及其长度.我的代码使用std :: basic_string并使用适当的转换调用这些方法.不幸的是,这些方法中的许多接受不同大小的字符串长度(即max(unsigned char),max(short)等等)并且我坚持编写代码以确保我的字符串实例不超过最大长度由低级API规定.
默认情况下,std :: basic_string实例的最大长度由size_t的最大值(max(unsigned int)或max(__ int64))绑定.有没有办法操纵std :: basic_string实现的traits和allocator实现,以便我可以指定自己的类型来代替size_t?通过这样做,我希望利用std :: basic_string实现中的任何现有边界检查,因此在执行转换时我不必这样做.
我的初步调查表明,如果不编写我自己的字符串类,这是不可能的,但我希望我忽略了一些东西:)
解决方法
你可以将自定义分配器传递给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()实现不会将其结果基于您使用的分配器,因此它仍然声称能够分配更多. (我不确定这是不是一个错误…).
但这肯定会让你以简单的方式对字符串的大小施加严格的限制.您甚至可以将max size设置为模板参数,这样您只需要为分配器编写一次代码.