C ++: dynamically allocating a member array of structures using a constructor other than the standard

If I have:

struct a_struct { int an_int; a_struct(int f) : an_int(f) {} a_struct() : an_int(0) {} }; class a_class { a_struct * my_structs; a_class() {...} }; 

I can do:

 a_class() {my_structs = new a_struct(1)} //or a_class() {my_structs = new a_struct [10]} 

But I can not:

 a_class() {my_structs = new a_struct(1) [10]} //or a_class() {my_structs = new a_struct() [10]} 

Is there any proper syntax to make this work? Or easy work around?

+8
c ++ memory-management arrays constructor struct
source share
4 answers

If using STL is an option, you can use std :: vector instead of a dynamic array.

I think this will work:

 std::vector<a_struct> my_structs; my_structs.assign(10, 1); 

If not, this should:

 my_structs.assign(10, a_struct(1)); 
+5
source share

You can allocate a raw piece of memory and use the new placement to initialize each struct :

 int number_of_structs = 10; my_structs = (a_struct*)new unsigned char[sizeof(a_struct) * number_of_structs]; // allocate a raw chunk of memory a_struct* p = m_structs; for (int i=0; i<number_of_structs; i++) { new (p) a_struct(i); p++; } 

See also: What is used to β€œpost new”?

+3
source share

You can use an array of pointers for pointers. Then you can create an array that will contain pointers to a_struct (), so you can later decide which constructor to use:

 class a_class { a_struct ** my_structs; a_class() { my_structs = new a_struct* [10]} void foo () { my_structs[0] = new a_struct(1); my_structs[5] = new a_struct("some string and float constructor", 3.14); } }; 
0
source share

You cannot do this directly on any particular parameterized constructor. However you can do

 a_struct *my_struct[10] = {}; // create an array of pointers for (int i = 0; i < 10; i++) my_struct[i] = new a_struct(i); // allocate using non-default constructor 

When you are going to de-allocate memory,

 for (int i = 0; i < 10; i++) delete my_struct[i] // de-allocate memory 

I suggest using the std::vector container instead of going through this process.

0
source share

All Articles