Initializer list for dynamic arrays?

后端 未结 5 1620
一个人的身影
一个人的身影 2020-11-30 14:44

It is possible to give an initializer list to the definition of a static array. Example:

int main()
{
  int int_static[2] = {1,2};
}

Is a s

5条回答
  •  既然无缘
    2020-11-30 15:47

    No, you cannot do that.

    I think C++ doesn't allow this because allowing such thing doesn't add any nice-to-have feature to the language. In other words, what would be the point of dynamic array if you use a static initializer to initialize it?

    The point of dynamic array is to create an array of size N which is known at runtime, depending on the actual need. That is, the code

    int *p = new int[2]; 
    

    makes less sense to me than the following:

    int *p = new int[N]; //N is known at runtime
    

    If that is so, then how can you provide the number of elements in the static initializer because N isn't known until runtime?

    Lets assume that you're allowed to write this:

    int *p = new int[2] {10,20}; //pretend this!
    

    But what big advantage are you getting by writing this? Nothing. Its almost same as:

    int a[] = {10,20};
    

    The real advantage would be when you're allowed to write that for arrays of N elements. But then the problem is this:

     int *p = new int[N] {10,20, ... /*Oops, no idea how far we can go? N is not known!*/ };
    

提交回复
热议问题