I’m developing a class to read a WAV file. The class should produce a vector for each channel (left/right), with the channel vectors in a vector of their own.
I’ve defined the loading method in the class as:
std::vector<std::vector<double> >* wavloader::load() throw(load_failed)
hence returning a pointer to this vector of vectors.
Inside the class I’ve allocated the memory for the top level vector, then created vectors for as many channels as I want, as follows:
std::vector<std::vector<double> >* audio_all_chans = new std::vector<std::vector<double> >;
std::vector<double> dummy_vector;
for(int chan_index = 0; chan_index<n_channels; chan_index++)
(*audio_all_chans).push_back(dummy_vector);
I then run through the file, and fill each of the vectors with the appropriate samples.
While the top level ‘vector of vectors’ is assigned using new, I’m concerned that the individual ‘channel’ vectors (generated with the dummy_vector) are in a way allocated on the stack.
When I leave the class, will the containing vectors go out of scope and be liable to be overwritten?
The program compiles with no warning at all, valgrind is completely happy with it, and I still get correct values from the returned pointer with the class deleted, but I’m a bit concerned there could be something insidious going on!
I know it is scary, but the way you did it was fine. A good rule of thumb is to look at the number of
*s in your declaration, anddeletethat many items. So you have a pointer to a dynamically allocated vector. Good, you need to delete that.What about inside? Well that vector held pointers to other vectors, then we would be responsible for getting rid of those, but since you just have vectors in there, they will go out of scope and be deleted.