Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the basic use of aligned_storage?

Tags:

c++

What is the basic usage of std::tr1::aligned_storage ? Can it be used as auto memory for a data type Foo like the one below?

   struct Foo{...};
   std::tr1::aligned_storage<sizeof(Foo)
        ,std::tr1::alignment_of<Foo>::value >::type buf;
   Foo* f = new (reinterpret_cast<void*>(&buf)) Foo();
   f->~Foo();

If so, what about storing multiple Foo in the buf like,

    std::tr1::aligned_storage<5*sizeof(Foo)
            ,std::tr1::alignment_of<Foo>::value >::type buf;
    Foo* p = reinterpret_cast<Foo*>(&buf);
    for(int i = 0; i!= 5; ++i,++p)
    {
        Foo* f = new (p) Foo();
    }

Are they valid programs? Is there any other use case for it ? Google search only yields the documentation about aligned_storage, but very little about the usage of it.

like image 754
abir Avatar asked Jul 04 '09 15:07

abir


1 Answers

Well, apart from your use of reinterpret_cast, it looks ok to me. (I'm not 100% sure on the second one).

The problem with reinterpret_cast is that it makes no guarantees about the result of the cast, only that if you cast the result back to the original type, you get the original value. So there is no guarantee that the result of the cast will contain the same bit pattern, or point to the same address.

As far as I know, a portable solution for casting a pointer x to a type T* is static_cast<T*>(static_cast<void*>(x)), since static_cast to and from void* is guaranteed to turn a pointer to the same address.

But that's only tangentially related to your question. :)

like image 161
jalf Avatar answered Nov 03 '22 15:11

jalf