Creating array of objects on the stack and heap

前端 未结 5 1267
慢半拍i
慢半拍i 2020-12-01 07:12

Consider the following code:

class myarray
{
    int i;

    public:
            myarray(int a) : i(a){ }

}

How can you create an array of

5条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 07:19

    Since C++11 std::array is available for arrays allocated on the stack. It wraps T[size] providing the interface of std::vector, but the most of the methods are constexpr. The downside here is that you never know when you overflow the stack.

    std::array stack_array; // Size must be declared explicitly.VLAs
    

    For arrays allocated with heap memory use std::vector. Unless you specify a custom allocator the standard implementation will use heap memory to allocate the array members.

    std::vector heap_array (3); // Size is optional.
    

    Note that in both cases a default constructor is required to initialize the array, so you must define

    myarray::myarray() { ... }
    

    There are also options to use C's VLAs or C++'s new, but you should refrain from using them as much as possible, because their usage makes the code prone to segmentation faults and memory leaks.

提交回复
热议问题