Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer wrapper for insertion

Tags:

c++

c++11

stl

Can someone tell me if there is a datatype in C++/STL that allows me to solve the following problem comfortably:

  • I have a preallocated contiguous area of memory representing an array of objects of type T.
  • I have a raw pointer ptrEnd to this area which points right after the last object of the area.
  • I have a pointer ptrCurrent that points to some position inside this area.

Now what I want is some kind of wrapper class that helps me insert new elements into this area. It should have some kind of "append" function which basically does the following things

  • Assign *ptrCurrent the value of object to insert
  • Increment ptrCurrent by one.
  • Omit the aforementioned steps if ptrCurrent >= ptrEnd. Return an error instead (or a false to indicate failure).

I could write something like this myself, but I wanted to ask first if there is a class in C++ STL that allows me to solve this problem more elegantly.

Thanks for your help.

like image 668
Desperado17 Avatar asked Nov 19 '25 14:11

Desperado17


1 Answers

There is a convenient feature for exactly this in C++17, polymorphic allocators. More specifically, this is what you want:

std::pmr::monotonic_buffer_resource buffer(sizeof(T) * 256);
    // Buffer that can hold 256 objects of type `T`.

std::pmr::vector<T> vec(&buffer);
    // The vector will use `buffer` as the backing storage.

live godbolt.org example

like image 73
Vittorio Romeo Avatar answered Nov 21 '25 05:11

Vittorio Romeo