Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char array as storage for placement new

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?

like image 634
bluescarni Avatar asked Jan 03 '11 08:01

bluescarni


1 Answers

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<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

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

char storage [[align(my_class)]] [sizeof(my_class)];
like image 171
GManNickG Avatar answered Sep 18 '22 07:09

GManNickG