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,还是应该使用static_castvia void*?
(一个)
unsigned short v16;
char* p = static_cast<char*>(static_cast<void*>(&v16));
p[1] = ... some char value
p[0] = ... some char value
Run Code Online (Sandbox Code Playgroud)
或(b)
unsigned short v16;
char* p = reinterpret_cast<char*>(&v16);
p[1] = ... some char value
p[0] = ... some char value
Run Code Online (Sandbox Code Playgroud)
根据static_cast和reinterpret_cast对std :: aligned_storage的回答都应该是等价的 -
- 如果T1和T2都是标准布局类型,并且T2的对齐要求不比T1更严格
我倾向于reinterpret_cast为是基本上我在做什么,不是吗?
还有其他需要考虑的事情,特别是我们正在编译的Visual-C++和VC8版本吗?(x86只有atm.)