I am reading about c++ allocators and the deallocate function has sentence that got my attention:
The argument n must be equal to the first argument of the call to allocate() that originally produced p; otherwise, the behavior is undefined.
Why is that? Why couldn't one deallocate part of the allocated memory, stupid example:
#include <memory>
#include <string>
int main()
{
std::allocator<std::string> alloc;
auto const p = alloc.allocate(20);
alloc.deallocate(p+10, 10);
return 0;
}
Some allocators might be able to do that. The C++ specification only says what all implementations of the abstract allocator interface, Alloc<T>
, are required to do. The committee decided not to require the feature you are asking about.
I don't have the C++ Rationale on this computer, but I suspect that the feature you are asking about is not required because the C memory allocator functions ( malloc
and free
) cannot do it, 1 and the C++ committee wanted it to be possible to implement the C++ library on top of the C library.
1 yes, realloc
can do some cases of this, but not all of them
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.