sbi had the best answer for plain arrays, but didn't give an example. So...
You should use placement new:
char *place = new char [sizeof(Foo) * 10000];
Foo *fooArray = reinterpret_cast<Foo *>(place);
for (unsigned int i = 0; i < 10000; ++i) {
new (fooArray + i) Foo(i); // Call non-default constructor
}
Keep in mind that when using placement new, you are responsible for calling the objects' destructors -- the compiler won't do it for you:
// In some cleanup code somewhere ...
for (unsigned int i = 0; i < 10000; ++i) {
fooArray[i].~Foo();
}
// Don't forget to delete the "place"
delete [] reinterpret_cast<char *>(fooArray);
This is about the only time you ever see a legitimate explicit call to a destructor.
NOTE: The first version of this had a subtle bug when deleting the "place". It's important to cast the "place" back to the same type that was newed. In other words, fooArray must be cast back to char * when deleting it. See the comments below for an explanation.
extern Foo foo[100];and then already refer to the array, as long as later you define it and then it needs all the initializers :)extern, but thought I ought to check it really works before posting, and you beat me to it. I don't think you even need to define it, as long as you don't reference it.std::array: codepad.org/O4bP8KO9 :) I suspect that's the closest one can get - but at least it's a native real array inside. @David, becausevectordynamically allocates, so it's overkill i think. In C++0x with the codepad code, we may even be able toconstexprall involved functions (if we refrain from using reference parameters), and benefit from static initialization to avoid the initialization-order fiasco, i think.