char array as storage for placement new

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

    The char array may not be aligned correctly for the size of myclass. On some architectures, that means slower accesses, and on others, it means a crash. Instead of char, you should use a type whose alignment is equal to or greater than that of the struct, which is given by the largest alignment requirement of any of its members.

    #include 
    
    class my_class { int x; };
    
    int main() {
        uint32_t storage[size];
        new(storage) my_class();
    }
    

    To allocate enough memory for one my_class instance, I think size ought to be sizeof(my_class) / sizeof(T), where T is whichever type you use to get the correct alignment.

提交回复
热议问题