How to create a dynamically allocated array of objects and not use the default constructor?

后端 未结 2 848
暗喜
暗喜 2021-01-19 05:06

The dynamically created array of objects need to use a non-default constructor, and the problem I\'m running into I think is the syntax. In my mind, the fact that I\'m able

相关标签:
2条回答
  • 2021-01-19 05:46

    new expression allows only default initialization, you can not do this within single new expression. What you could do is allocate raw memory and construct objects one by one using placement new (see this answer in Object array initialization without default constructor)

    Or yet even better, don't use C-style arrays. Instead, use some STL container such as std::vector and it's constructor, where the 2nd argument is a value that will be used to initialize elements:

    std::vector<IntegerSet> integers(5, IntegerSet(this->getLength()) );
    
    0 讨论(0)
  • 2021-01-19 05:46

    There is an easy way out of this problem: add a default constructor to IntegerSet that does not acquire memory and any other resources. This way you can allocate an array of IntegerSet with new and then fill each element of the array on the next step.

    Even better solution: use std::vector<IntegerSet> and emplace_back() to initialize each element of the array using a non-default constructor.

    0 讨论(0)
提交回复
热议问题