Aligning a static array with std :: aligned_storage

I am trying to implement 16-byte alignment of a simple static array using the std :: aligned_storage pattern :

#include <type_traits> int main() { const size_t SIZE = 8; using float_16 = std::aligned_storage<sizeof(float) * SIZE, 16>::type; float_16 mas; new(&mas) float[SIZE];//Placement new. Is this necessary? mas[0]=1.f;//Compile error while attempting to set elements of aligned array } 

I get the following compilation error:

no match for "operator []" in "mas [0]"

Then I tried to use an explicit expression for the pointer:

 float* mas_ = reinterpret_cast<float*>(mas); 

but this also leads to a compilation error:

Incorrect listing from type "float_16 {aka std :: aligned_storage <32u, 16u> :: type}" to enter "float *"

Can someone suggest me how to properly configure a static array using std :: aligned_storage ?

+6
source share
3 answers

You can use:

 float* floats = new (&mas) float[SIZE]; 

and then you can use:

 floats[0] = 1.f; 

no reinterpret_cast :

+7
source

mas not a pointer. reinterpret_cast should include only a pointer, a reference or integral types, and only in some combinations: pointers to and from integral types, pointers to pointers, links to links, or an integral type for yourself. In this case, you are trying to apply the std::aligned_storage<32u, 16u>::type pointer to the pointer. The best you could get from this would be a reference to casting a pointer, but that is not permitted by & dagger ;.

Try pointing your address to another type of pointer instead: reinterpret_cast<float*>(&mas); .


& cross for fun: the worst thing you could get would be if std::aligned_storage<32u, 16u>::type was a pointer type. This is doubtful since 32-byte pointers are not shared, but this can happen for std::aligned_storage<8u, 8u>::type , for example, in a very nasty standard library. Let me call it Hell ++. Thus, in Hell ++, it will compile fine, and you end up leading the type of pointer to another type of pointer, and then do all the bad things on it like dereferencing it. This would be a disaster, because if std::aligned_storage<32u, 16u>::type was a pointer type, the objects would not have an address for the store, but instead they would be the store.

+5
source

Just do

 alignas(16) float mas[SIZE]; 

std::aligned_storage - C ++ 03 release coming from boost .

+1
source

Source: https://habr.com/ru/post/953242/


All Articles