Reputation: 14869
I am trying to use a buffer of char
on the stack as storage for some other type of data.
As test I started with the most basic int
but casting pointer of chars to pointer of integer doesn't compile.
char buf[256];
int* l = static_cast<int*>(buf);
*l = 20;
The error I got is
error: invalid static_cast from type ‘char*’ to type ‘int*’
Being these primitive data I was expecting this to work: do you know what is the mechanics behind this specific case?
I sorted out by using reinterpet_cast
but I'd like to use static_cast
as this last should be more fast.
Upvotes: 1
Views: 5248
Reputation: 477010
You will need a reinterpret cast. Here's how it works with proper alignment:
#include <memory>
std::aligned_storage<20 * sizeof(int), alignof(int)>::type storage;
int * p = reinterpret_cast<int *>(&storage);
for (std::size_t i = 0; i != 20; ++i)
{
::new (p + i) int(i); // or "p[i] = i;"
}
Upvotes: 4