One other quick question. If I switch to using vectors, how will I handle allocation and deletion of the name field in the MIDIDevice structure? Would that be "std::vector<wchar_t> pName;" or something, then I either loop through and call clear on each one or hope that during destruction it does it automatically? |
Well, if you're on a voyage of discovery into the STL, I can thoroughly recommend looking at the
std::string class (defined in the <string> header file). It handles the memory management for a string so that you don't have to worry about it. It's much more suitable for strings than a vector of chars.
Oh, wait, you're using
wchar_t, not
char - so you'll want
std::wstring instead, which works the same way as
std::string but uses
wchar instead of
char.
If you're desperate to stick with dynamically allocating your
pName as an array, then the most sensible approach would be to create a destructor for your
MIDIDevice. In C++, structs and classes are identical (except for the default access), so a struct can have member functions just like a class.
If you write a destructor for your struct, and have that destructor delete
pName, then when the vector is destroyed, the following will hapopen:
- the vector class will destroy each element in turn
- when each element is destroyed, its destructor is called automatically
- the destructor for each element will free the memory used by
pName
The end result is that you don't need to specifically free the memory - the
MIDIDevice destructor will do it for you automatically when the
MIDIDevice instances are destroyed, and that will happen when the vector itself is destroyed.