typically, dynamic memory is avoided in favor of c++ containers.
if you feel you must use it, the class/struct pattern is typically to allocate the memory in the constructor, destroy it in the destructor, and in case you need it, reallocation / modification of the memory is done in some other member function (eg resize). When you run into this you will also find you need to hit the rules of 3/5 to provide an assignment operator (so you don't copy the POINTER but instead make a copy of the DATA into the new copy) and various other issues associated with those rules. If you just use the container as noted, you can clear up all these things, you no longer need explicit ctor/dtor/assignment/etc stuff as it will all just work (barring other complexities). For both containers and pointers, you have to serialize the data yourself if you need to write the object to a file/network/etc.
similarly, for allocation of the object itself, you are better off with a container than a pointer.
but if you need to do that, it is simply this pattern:
objectype * po = new objectype[size];
po[0] = something; //use it
delete[] po; //cleanup.
I can't advise enough to say:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
struct Test
{
TestHdr hdr;
string data;
};
Test * tp = new Test[10];
tp[0].data = "hello world";
cout << tp[0].data;
delete[] tp;
//same thing without the mess:
vector<test> tp(10);
tp[0].data = "hello world";
cout << tp[0];
| |
and if you need to make pointers everywhere, eg char* data inside, it gets a lot messier in a hurry.