Reputation: 1471
Lets say i have a class like this:
class LolClass {
LPWSTR* stuff;
LolClass::LolClass(LPWCHAR lols) {
stuff = new LPWSTR[100];
for (int i = 0; i < 100; i++) {
stuff[i] = new wchar_t[wcslen(lols)+1];
wcsncpy(stuffs[i], lols, wcslen(lols)+1);
}
}
LolClass::~LolClass() {
delete[] stuff;
}
}
so if i call
LolClass* veryfunny = new LolClass(L"lol!");
it would make me 100 lol's, problem is when i call
delete veryfunny;
it deletes the pointer array but not the individual wchar_t's, if i try and loop through the wchar_t's and delete them then i just crash and i dont know what to do since i know for fact that they are still there even after i delete veryfunny (i checked by passing one of the pointers outside the class)
Thanks!
Upvotes: 1
Views: 3983
Reputation: 1471
David Schwartz wins after all, the wchar's didnt let themselves be deleted because they werent null terminated
Upvotes: -1
Reputation: 477454
If you call
LolClass* veryfunny = new LolClass(L"lol!");
then you will eventually need to call:
delete veryfunny;
But for arrays, you need delete[]
: stuff[i] = new wchar_t[n]; delete [] stuff[i];
In your code, you need to first loop over stuff
and delete[]
the elements, and then delete[]
the array stuff
itself.
Or just use a std::vector<std::wstring>
.
Update: From what I understand, you're not actually worried about deleting *veryfunny
, but rather about how to write a correct destructor for LolClass
. Note that the destructor also gets invoked for global and automatic objects, e.g. { LolClass x(L"hello"); } /* boom */
, so it doesn't really matter how you instantiate an object for LolClass
. You have to get the class right in any case.
Upvotes: 6