As far as I know, C++ does not support an operator like 'realloc(void *, size_t)'
C++ does have std::realloc. But it is not (typically?) used to implement resizing of vector.
Then how could it be done to resize the buffer of std::vector without 'realloc' function?
Using following algorithm:
- allocate new array
- copy or move contents to the new array
- deallocate old array
Is it be done just by allocating new buffer, copy or move all elements and destructing previous buffer?
Yes.
I think it is inefficient.
Why do you think so? That's exactly what realloc does. Sure, realloc may sometimes be able to skip the copying depending on memory layout, which vector generally cannot. This is an unfortunate downside of vector compared to manually mallocated dynamic array, but it's not necessarily a significant downside.
There have been proposals to add reallocation support to standard allocators, which would allow the same optimisation if adopted into the standard: http://open-std.org/JTC1/SC22/WG21/docs/papers/2019/p0894r1.md
reallocis that it only works if memory can be expanded w/o changing the previously allocated and likely used memory. This is memory fragmentation and OS dependent - dougstd::vector,std::list, etc) make requests to an object called an allocator, which does the actual work of memory management, via a defined interface. Allocators and containers tend to be pretty carefully crafted for performance and correctness by the authors of your standard library (or compiler vendor). Before claiming they are inefficient, write code of your own that does the same thing, get it working correctly, and compare. (Beginners tend to over-estimate their ability to write efficient and correct code). - Peter