This is kind of a beginners question, but I haven't done C++ in a long time, so here goes...
I have a class that contains a dynamically allocated array, say
class A
{
int* myArray;
A()
{
myArray = 0;
}
A(int size)
{
myArray = new int[size];
}
~A()
{
// Note that as per MikeB's helpful style critique, no need to check against 0.
delete [] myArray;
}
}
But now I want to create a dynamically allocated array of these classes. Here's my current code:
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
arrayOfAs[i] = A(3);
}
But this blows up terribly. Because the new A
object created (with the A(3)
call) gets destructed when the for
loop iteration finishes, and this means that the internal myArray
of that A
instance gets delete []
-ed.
So I think my syntax must be terribly wrong? I guess there are a few fixes that seem like overkill, which I'm hoping to avoid:
- Creating a copy constructor for
A
. - Using
vector<int>
andvector<A>
so I don't have to worry about all this. - Instead of having
arrayOfAs
be an array ofA
objects, have it be an array ofA*
pointers.
I would think this is just some beginners thing where there's a syntax that actually works when attempting to dynamically allocate an array of things that have internal dynamic allocation.
(Also, style critiques appreciated, since it's been a while since I did C++.)
Update for future viewers: All of the answers below are really helpful. Martin's is accepted because of the example code and the useful "rule of 4," but I really suggest reading them all. Some are good, succinct statements of what's wrong, and some point out correctly how and why vector
s are a good way to go.