Reputation: 640
For example, as simplified as possible:
class thing{
public:
char* arr;
thing();
}
thing::thing{
arr = new char[1000];
}
If I create a dynamically allocated instance of thing
, then deallocate it with delete
, will the memory that was dynamically allocated by the constructor also be deallocated, or do I have to deallocate arr
first?
Upvotes: 1
Views: 760
Reputation: 42838
No, you will leak the allocated array. A char*
doesn't know it's supposed to delete
itself when it goes out of scope — it's simply pointing to that memory.
If you use the right tool for the right job though, i.e. change arr
to be a unique_ptr
then it will automatically know to free the memory you assigned to it once the thing
is deallocated.
Upvotes: 1
Reputation: 129374
Not as that class is written. You will need to declare a destructor that does delete [] arr;
- and you should follow the rule or three (or rule of five if you add move semantics).
Upvotes: 3