char array as storage for placement new

后端 未结 5 1633
[愿得一人]
[愿得一人] 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:18

    As people have mentioned here, this won't necessarily work due to alignment restrictions. There are several ways to get the alignment right. First, if you have a C++0x-compliant compiler, you can use the alignof operator to try to force the alignment to be correct. Second, you could dynamically-allocate the character array, since memory from operator new is guaranteed to be aligned in such a way that anything can use it correctly. Third, you could try storing the character array in a union with some type that has the maximum possible alignment on your system; I believe that this article has some info on it (though it's designed for C++03 and is certainly not as good as the alignof operator that's coming out soon).

    Hope this helps!

提交回复
热议问题