How to declare an array without specific size?

后端 未结 4 1351
情书的邮戳
情书的邮戳 2021-01-02 20:06

How can I declare an array without specific size as a class member? I want to set the size of this array immediately in the class constructor. Is it possible to do such thin

4条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-02 20:52

    C++ requires the size of an automatic storage array to be known at compile time, otherwise the array must be dynamically allocated. So you would need dynamic allocation at some level, but you don't have to concern yourself with doing it directly: just use an std::vector:

    #include 
    
    class Foo
    {
     public:
      Foo() : v_(5) {}
     private:
      std::vector v_;
    };
    

    Here, v_ is a vector holding ints, and is constructed to have size 5. The vector takes care of dynamic allocation for you.

    In C++14, you will have the option of using std::dynarray, which is very much like an std::vector, except that its size is fixed at construction. This has a closer match to the plain dynamically allocated array functionality.

提交回复
热议问题