Memory for the pointer itself will be deallocated when the object is destroyed, as it is for any class member. However, the array it points to won't be deleted - there is no way to know what the pointer points to, whether it was allocated by new
or new[]
or not dynamically allocated at all, or whether anything else still wants to use it. To avoid memory leaks, you should delete it, with the array form delete [] ms.nums;
, once you've finished with it.
Since it's often hard to do this correctly, why not use a library class to manage the array correctly for you?
#include <vector>
struct MyStruct
{
std::vector<int> nums;
};
MyStruct ms;
ms.nums.resize(4);
Now all the memory will be released automatically when ms
is destroyed; and the class is correctly copyable and (since C++11) efficiently movable.