9

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 cannot do:

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

Is there any correct syntax to get this to work? Or an easy work around?

Matt Munson
  • 2,903
  • 5
  • 33
  • 52

4 Answers4

5

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

I think that 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));
CariElf
  • 204
  • 2
  • 6
4

You could allocate a raw chunk of memory and use placement new 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++;
}

//When done should add code for deallocation to help people 
// to understand the full cycle of memory management.  
for (auto i=0; i<number_of_structs; ++i) {
    my_structs[i].~a_struct(); 
} 
delete[] my_structs;

See also: What uses are there for "placement new"?

Kemin Zhou
  • 6,264
  • 2
  • 48
  • 56
Tony the Pony
  • 40,327
  • 71
  • 187
  • 281
0

You could use an array of pointers to pointers. Then you can create the array that will hold pointers to a_struct(), so you can decide later 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);
    }
}; 
rtn
  • 127,556
  • 20
  • 111
  • 121
  • This does not allow you to pass around an array of structs (or pointer to the struct then use pointer math to move to the next element of the array). – iheanyi Aug 21 '14 at 20:20
0

You can't do it 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

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

Kemin Zhou
  • 6,264
  • 2
  • 48
  • 56
cpx
  • 17,009
  • 20
  • 87
  • 142
  • 1
    The advantage of `std::vector` in this case is that all `my_struct`s will be in a contiguous memory block. – Xeo May 26 '11 at 23:28
  • This does not allow you to pass around an array of structs (or pointer to the struct then use pointer math to move to the next element of the array) – iheanyi Aug 21 '14 at 20:20