While the title might not be very specific, it refers to the general understanding on how much we can play with reinterpret_cast<>()
while dealing with memory buffers. Considering the following code:
struct foo { };
int main() {
auto buffer = reinterpret_cast<foo*>(new char[3 * sizeof(foo)]);
new (buffer) foo;
new (buffer + 1) foo;
std::destroy(buffer, buffer + 2);
delete[] reinterpret_cast<char*>(buffer);
}
I asked myself a question - is this safe and correct?
When searching various sources of information, I encountered a lot of examples that used alignas
. As it can be seen in this question, (at to least my understanding), the problem of not aligning was caused by a specific offset of the memory buffer pointer. If my understading is incorrect, please correct me.
The question itself is - Does this code safely mimicks the memory buffer of, let's say, std::vector<foo>
? What does it lack? Is the alignas
required here? Where would I apply it? How to minimally construct an example of what vector does in this case?