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;
EDIT:私は予想通り、これが動作することを確認するテストをやったし。次のコードはそれをテストします。
s += s
は(私の限界は64Kのちょうど短いため)、トップの上に置くと
std::bad_alloc
例外が発生します続く
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;
}
。残念ながら、gccのstd::basic_string::max_size()
実装は、使用しているアロケータにその結果を基づいていないため、さらに割り当てることができると主張します。 (これはバグかどうかは分かりませんが...)。
しかし、これは間違いなく簡単な方法で文字列のサイズに厳しい制限を課すことを可能にします。最大サイズをテンプレートパラメータにして、アロケータのコードを一度書くだけで済むようにすることもできます。
intテンプレートパラメータを追加し、max_size()にNを返します。次に、typedef std :: basic_string 、my_allocator > my256stringを実行できます。 –
jmucchiello
私はテンプレート引数として 'size_type'を公開することは有益だろうと思っています。なぜなら、ユーザーは自由に任意の' size_type'が与えられた文字列インスタンスに最適であるように選択することができます。次に、部分テンプレートの特殊化は、この型を 'basic_string'で素敵にするのに役立ちます。 –