Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is there no reallocation functionality in C++ allocators?
    primarykey
    data
    text
    <p>In C the standard memory handling functions are <code>malloc()</code>, <code>realloc()</code> and <code>free()</code>. However, C++ stdlib allocators only parallel two of them: there is no reallocation function. Of course, it would not be possible to do exactly the same as <code>realloc()</code>, because simply copying memory is not appropriate for non-aggregate types. But would there be a problem with, say, this function:</p> <pre><code>bool reallocate (pointer ptr, size_type num_now, size_type num_requested); </code></pre> <p>where</p> <ul> <li><code>ptr</code> is previously allocated with the same allocator for <code>num_now</code> objects;</li> <li><code>num_requested</code> >= <code>num_now</code>;</li> </ul> <p>and semantics as follows:</p> <ul> <li>if allocator can expand given memory block at <code>ptr</code> from size for <code>num_now</code> objects to <code>num_requested</code> objects, it does so (leaving additional memory uninitialized) and returns <code>true</code>;</li> <li>else it does nothing and returns <code>false</code>.</li> </ul> <p>Granted, this is not very simple, but allocators, as I understand, are mostly meant for containers and containers' code is usually complicated already.</p> <p>Given such a function, <code>std::vector</code>, say, could grow as follows (pseudocode):</p> <pre><code>if (allocator.reallocate (buffer, capacity, new_capacity)) capacity = new_capacity; // That's all we need to do else ... // Do the standard reallocation by using a different buffer, // copying data and freeing the current one </code></pre> <p>Allocators that are incapable of changing memory size altogether could just implement such a function by unconditional <code>return false;</code>.</p> <p>Are there so few reallocation-capable allocator implementation that it wouldn't worth it to bother? Or are there some problems I overlooked?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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