No, it's a rubbish idea, even if it was valid C++ and did what you thought it did. First off in you example there was no need for a dynamically allocated array. Second if you want dynamic arrays then use a
vector
. If you can't use a
vector
(for some reason) use a
std::shared_ptr
or
std::unique_ptr
.
So using ptr objects:
#include <memory>
struct exam{
int id;
char name[10];
};
int main()
{
std::unique_ptr<int> p1( new int [10] );
std::unique_ptr<char> p2( new char[10] );
std::unique_ptr<double> p3( new double[10] );
std::unique_ptr<exam> p4( new exam() );
}
Not a delete in sight, no need to call loads of functions to free memory.
Or preferably using
std::vector
:
#include <vector>
struct exam{
int id;
char name[10];
};
int main()
{
std::vector<int>< p1( 10 );
std::vector<char> p2( 10 );
std::vector<double> p3( 10 );
std::unique_ptr<exam> p4( new exam() );
}
Or even more preferably using automatic objects:
struct exam{
int id;
char name[10];
};
int main()
{
int p1[10];
char p2[10];
double p3[10];
exam p4;
}
Basically the first rule is don't fiddle with memory directly. Sometimes you have to but unless one of the other C++ mechanisms will fo the job. The second rule is that if you do have to use the heap then assign the returned value from new to a ptr object so the destructor gets called automagically.