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的文档,但关于它的使用情况却很少.
好吧,除了你的使用reinterpret_cast
,它看起来还不错.(我对第二个不是100%肯定).
问题reinterpret_cast
是它不能保证转换的结果,只有当你将结果转换回原始类型时,才能获得原始值.因此,无法保证转换的结果将包含相同的位模式,或指向相同的地址.
据我所知,用于将指针x转换为类型T*的可移植解决方案是static_cast<T*>(static_cast<void*>(x))
,因为static_cast
往返void*
保证将指针转向同一地址.
但这与你的问题只是切线相关.:)
归档时间: |
|
查看次数: |
4035 次 |
最近记录: |