I want to create in C++ an array of Objects without using STL.
How can I do this?
How could I create array of Object2, which has no argumentless constructor (default constructor)?
feedback
|
If the type in question has an no arguments constructor, use
don't forget to call
If it doesn't have such a constructor use
Again, don't forget to deallocate the array when you no longer need it. | |||||||||||||||||||||
feedback
|
If no default constructor is available, you will need an array of pointers, and then loop over that array to initialize each of the pointers. | |||||
feedback
|
Later on you will have to walk through the array and deallocate each member individually:
| |||||||
feedback
|
The obvious question is why you don't want to use the STL. Assuming you have a reason, you would create an array of objects with something like You can't do that with an object with no constructor that doesn't take arguments. In that case, I think the best you could do is allocate some memory and use placement new. It isn't as straightforward as the other methods. | |||
feedback
|
Use an array of pointers to Object2:
Or, alternatively, without the use of shared_ptr:
| |||||||||||||
feedback
|
You can do what | ||||
feedback
|
Assuming that your class is Base and you have a one argument constructor
| |||||||
feedback
|
| |||||||||||||
feedback
|
If you genuinely need an array (contiguous sequence of objects) of a non-default constructible type and for some reason you cannoy user This is very hard to do reliably; this should help to show why. This snippet includes some defence against exceptions but is more than likely not robust against all failures.
| |||||||||||||
feedback
|