可以利用std :: basic_string来实现具有长度限制的字符串吗?

Ste*_*idi 6 c++ string templates stl stdstring

我正在使用一个低级API,它接受一个char*和数字值来分别表示一个字符串及其长度.我的代码使用std::basic_string适当的翻译并调用这些方法.不幸的是,这些方法中的许多都接受不同大小的字符串长度(即max(unsigned char),max(short)等等),而且我很难编写代码以确保我的字符串实例不超过规定的最大长度.低级API.

默认情况下,std::basic_string实例的最大长度受最大值size_t(max(unsigned int)或max(__int64))的约束.有没有办法操纵实现的traits和allocator实现,std::basic_string以便我可以指定自己的类型来代替size_t?通过这样做,我希望利用实现中的任何现有边界检查std::basic_string,因此在执行转换时我不必这样做.

我的初步调查表明,如果不编写我自己的字符串类,这是不可能的,但我希望我忽略了一些东西:)

Eva*_*ran 5

您可以传递一个自定义分配器,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;
    }
};
Run Code Online (Sandbox Code Playgroud)

然后你可以这样做:

typedef std::basic_string<char, std::char_traits<char>, my_allocator<char> > limited_string;
Run Code Online (Sandbox Code Playgroud)

编辑:我刚刚做了一个测试,以确保它按预期工作.以下代码对其进行测试.

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;
}
Run Code Online (Sandbox Code Playgroud)

最后一个s += s将它放在顶部并导致std::bad_alloc异常,(因为我的限制只是短缺64k).不幸的是,gcc的std::basic_string::max_size()实现不会将结果基于您使用的分配器,因此它仍然声称能够分配更多.(我不确定这是不是一个错误...).

但这肯定会让你以简单的方式对字符串的大小施加严格的限制.您甚至可以将max size设置为模板参数,这样您只需要为分配器编写一次代码.