Dynamic array in Stack?

前端 未结 6 686
眼角桃花
眼角桃花 2020-11-27 21:25

Is this correct ? This is compiled with g++ (3.4) sucessfully.

int main()
{
    int x = 12;
    char pz[x]; 
}
6条回答
  •  广开言路
    2020-11-27 22:07

    Allocating arrays with variable length on the stack is a good idea, because it fast and doesn't fragment the memory. But C++ Standard unfortunately doesn't support it. You could do this by using template wrapper to alloca function. But using alloca is not really a standard conforming.

    Standard way is to use std::vector with custom allocator if you want to avoid memory fragmentation and speedup memory allocations. Take a look on boost::pool_alloc for a good sample of fast allocator.

提交回复
热议问题