aligned_storage的基本用法是什么?

abi*_*bir 11 c++

std :: tr1 :: aligned_storage的基本用法是什么?它可以用作数据类型Foo的自动存储器,如下所示吗?

   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();
Run Code Online (Sandbox Code Playgroud)

如果是这样,那么在buf中存储多个Foo就像,

    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();
    }
Run Code Online (Sandbox Code Playgroud)

他们是有效的计划吗?它还有其他用例吗?Google搜索只会生成有关aligned_storage的文档,但关于它的使用情况却很少.

jal*_*alf 9

好吧,除了你的使用reinterpret_cast,它看起来还不错.(我对第二个不是100%肯定).

问题reinterpret_cast是它不能保证转换的结果,只有当你将结果转换回原始类型时,才能获得原始值.因此,无法保证转换的结果将包含相同的位模式,或指向相同的地址.

据我所知,用于将指针x转换为类型T*的可移植解决方案是static_cast<T*>(static_cast<void*>(x)),因为static_cast往返void*保证将指针转向同一地址.

但这与你的问题只是切线相关.:)

  • 实际上,在当前以及(草案)C++ 1x标准中,不允许`reinterpret_cast`来自或来自`void*`(尽管实现允许它).所以你真的应该使用`static_cast`.在C++ 1x中,对于标准布局类型,`reinterpret_cast <T*>(u)`是根据`static_cast <T*>(static_cast <void*>(u))`定义的. (6认同)
  • 是的,我不知道一个编译器,其中重新解释实际上是一个问题(我认为它们将使它按照你在C++ 0x中所期望的那样工作),但根据标准,它是未定义的行为.static_cast技巧应该适用于任何指针类型. (3认同)