Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>you can pass a custom allocator to <code>std::basic_string</code> which has a max size of whatever you want. This should be sufficient. Perhaps something like this:</p> <pre><code>template &lt;class T&gt; 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&amp; reference; typedef const T&amp; const_reference; pointer address(reference r) const { return &amp;r; } const_pointer address(const_reference r) const { return &amp;r; } my_allocator() throw() {} template &lt;class U&gt; my_allocator(const my_allocator&lt;U&gt;&amp;) throw() {} ~my_allocator() throw() {} pointer allocate(size_type n, void * = 0) { // fail if we try to allocate too much if((n * sizeof(T))&gt; max_size()) { throw std::bad_alloc(); } return static_cast&lt;T *&gt;(::operator new(n * sizeof(T))); } void deallocate(pointer p, size_type) { return ::operator delete(p); } void construct(pointer p, const T&amp; val) { new(p) T(val); } void destroy(pointer p) { p-&gt;~T(); } // max out at about 64k size_type max_size() const throw() { return 0xffff; } template &lt;class U&gt; struct rebind { typedef my_allocator&lt;U&gt; other; }; template &lt;class U&gt; my_allocator&amp; operator=(const my_allocator&lt;U&gt; &amp;rhs) { (void)rhs; return *this; } }; </code></pre> <p>Then you can probably do this:</p> <pre><code>typedef std::basic_string&lt;char, std::char_traits&lt;char&gt;, my_allocator&lt;char&gt; &gt; limited_string; </code></pre> <p><strong>EDIT:</strong> I've just done a test to make sure this works as expected. The following code tests it.</p> <pre><code>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 &lt;&lt; s.max_size() &lt;&lt; std::endl; std::cout &lt;&lt; s.size() &lt;&lt; std::endl; } </code></pre> <p>That last <code>s += s</code> will put it over the top and cause a <code>std::bad_alloc</code> exception, (since my limit is just short of 64k). Unfortunately gcc's <code>std::basic_string::max_size()</code> implementation does not base its result on the allocator you use, so it will still claim to be able to allocate more. (I'm not sure if this is a bug or not...).</p> <p>But this will definitely allow you impose hard limits on the sizes of strings in a simple way. You could even make the max size a template parameter so you only have to write the code for the allocator once.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload