C++ using new to create object array with initializer
Solution 1
You can:
cls *arr = new cls[3] { 2, 2, 2 };
If you use std::vector
, you can:
std::vector<cls> v(3, cls(2));
or
std::vector<cls> v(3, 2);
Solution 2
Use a vector.
If you insist on using a dynamically allocated array instead of std::vector
, you have to do it the hard way: allocate a block of memory for the array, and then initialize all the elements one by one. Don't do this unless you really can't use a vector! This is only shown for educational purposes.
cls* arr = static_cast<cls*>(::operator new[](N*sizeof(cls)));
for (size_t i = 0; i < N; i++) {
::new (arr+i) cls(2);
}
// ::delete[] arr;
Solution 3
You can also use vectors
#include <vector>
using namespace std;
class cls{
public:
cls(int a):value(a){}
private:
int value;
};
int main() {
vector<cls> myArray(100, cls(2));
return 0;
}
That creates a vector (an array) with 100 cls objects initialized with 2;
CyberLuc
Updated on June 05, 2022Comments
-
CyberLuc almost 2 years
I wrote a class, something like this (just for demonstration) :
class cls{ public: cls(int a):value(a){} private: int value; };
And I want to dynamically create an array, each element initialized to a specific value like 2:
cls *arr = new cls[N](2);
But g++ reported 'error: parenthesized initializer in array new'.
I searched the Internet, but only to find similar questions about basic types like
int
anddouble
, and answer is NO WAY.Suppose the class must be initialized, how to solve the problem? Do I have to abandon constructer?
-
CyberLuc almost 10 yearsThanks. I tried vector and use constructor to print a string at the same time. The string shows only once, but I checked every element is initialized.
-
CyberLuc almost 10 yearsThanks. I tried vector and use constructor to print a string at the same time. The string shows only once, but I checked every element is initialized. Seems vector only initializes once, then copy the one to the remaining objects.
-
CyberLuc almost 10 yearsThanks, vector is enough for me.
-
keltar almost 10 years@Twisx constructor called when you used
cls(2)
manually and passed it to vector initialisation. Then copy constructor used to fill elements. -
CyberLuc almost 10 years@keltar I got it! Thanks!
-
mkrufky over 6 yearsThank you for this obscure answer. It came in very handy for me in my use case: I needed a pointer to an array of objects that lack a default constructor to be queued to another thread which will later destroy the memory when it's no longer needed. I wouldn't have been able to do that with a vector. I'll admit it's less pretty, but it gets the job done.