char数组作为存储的新的 [英] char array as storage for placement new
本文介绍了char数组作为存储的新的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下是合法的C ++是否有明确的行为?
Is the following legal C++ with well-defined behaviour?
class my_class { ... };
int main()
{
char storage[sizeof(my_class)];
new ((void *)storage) my_class();
}
或者这是有问题的,因为指针转换/对齐的注意事项?
Or is this problematic because of pointer casting/alignment considerations?
推荐答案
是的,这有问题。
虽然存在各种技巧来获得正确对齐的存储,但最好使用Boost或C ++ 0x aligned_storage
,它们隐藏了你的这些技巧。
While various tricks exist to get storage with proper alignment, you're best off using Boost's or C++0x's aligned_storage
, which hide these tricks from you.
然后你只需要:
// C++0x
typedef std::aligned_storage<sizeof(my_class),
alignof(my_class)>::type storage_type;
// Boost
typedef boost::aligned_storage<sizeof(my_class),
boost::alignment_of<my_class>::value>::type storage_type;
storage_type storage; // properly aligned
new (&storage) my_class(); // okay
注意,在C ++ 0x中,使用属性,你可以这样做: / p>
Note that in C++0x, using attributes, you can just do this:
char storage [[align(my_class)]] [sizeof(my_class)];
这篇关于char数组作为存储的新的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文