char array as storage for placement new

后端 未结 5 1637
[愿得一人]
[愿得一人] 2020-12-31 16:43

Is the following legal C++ with well-defined behaviour?

class my_class { ... };

int main()
{
    char storage[sizeof(my_class)];
    new ((void *)storage) m         


        
5条回答
  •  旧巷少年郎
    2020-12-31 17:13

    Yes, it's problematic. You simply have no guarantee that the memory is properly aligned.

    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.

    Then you just need:

    // C++0x
    typedef std::aligned_storage::type storage_type;
    
    // Boost
    typedef boost::aligned_storage::value>::type storage_type;
    
    storage_type storage; // properly aligned
    new (&storage) my_class(); // okay
    

    Note that in C++0x, using attributes, you can just do this:

    char storage [[align(my_class)]] [sizeof(my_class)];
    

提交回复
热议问题