Allocating struct with variable length array member

后端 未结 5 467
醉话见心
醉话见心 2020-12-01 22:24

I know I can do new char[n] to create an array of n chars. This works even when n is not a compile time constant.

But lets say

5条回答
  •  庸人自扰
    2020-12-01 22:44

    You can use placement new:

    #include 
    
    struct Test {
        size_t size;
        char a[1];
    
        static Test* create(size_t size)
        {
            char* buf = new char[sizeof(Test) + size - 1];
            return ::new (buf) Test(size); 
        }
    
        Test(size_t s) : size(s)
        {
        }
    
        void destroy()
        {
            delete[] (char*)this;
        }
    };
    
    int main(int argc, char* argv[]) {
        Test* t = Test::create(23);
        // do whatever you want with t
        t->destroy();
    }
    

提交回复
热议问题