Reputation: 313
I have declared dynamic array inside int main so my question is that how to delete and release that array in the destructor?? or else I should release that inside main.
delte[] ptr ---
Please answer this simple question to me. Thanks in advance
I have also implement class but declared dynamic array inside main so whats the use of destructor? should I delete inside destructor?
Upvotes: 0
Views: 444
Reputation: 31519
Every scope has exit points. You make use of this and destructors to implement the RAII idiom. Since you have no class to wrap your data in, you can use the boost library to define actions to be taken on scope exit.
{ // some scope, maybe that of a main function
double *new_ar = new double[15];
BOOST_SCOPE_EXIT(new_ar) {
delete[] new_ar;
} BOOST_SCOPE_EXIT_END
} // end of scope
Upvotes: 0
Reputation: 110658
The program itself doesn't have a destructor. It starts at the beginning of main
and ends at the end of main
. If you need to deallocate some memory you allocated at the beginning of main
, you should do it before main
ends:
int main() {
int* arr = new int[10];
// Do lots of work
delete[] arr;
}
Of course, it would be much better if you encapsulated this memory allocation inside a class using RAII, so that you don't have to deal with it manually. In fact, types already exist for this - the standard library containers (such as std::vector
or std::array
).
Upvotes: 1