char数组作为放置新的存储

blu*_*rni 8 c++ pointers placement-new

以下合法C++是否具有明确定义的行为?

class my_class { ... };

int main()
{
    char storage[sizeof(my_class)];
    new ((void *)storage) my_class();
}
Run Code Online (Sandbox Code Playgroud)

或者这是因为指针投射/对齐考虑因素有问题吗?

GMa*_*ckG 14

是的,这是有问题的.您根本无法保证内存已正确对齐.

虽然存在各种技巧来获得正确对齐的存储,但最好使用Boost或C++ 0x aligned_storage,这会隐藏这些技巧.

那么你只需要:

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

请注意,在C++ 0x中,使用属性,您可以这样做:

char storage [[align(my_class)]] [sizeof(my_class)];
Run Code Online (Sandbox Code Playgroud)