C++ – Using Raw Pointers with std::vector

c

I am currently maintaining a code that makes liberal use of raw pointers where std::vector would be a better option. Worse, these pointers are not always properly handled (when run using Intel Inspector, I get the warning message "Warning: Only the first 100,000 memory issues are reported"). As such, I have been slowly changing all instances of raw pointers to std::vector. However, there are several functions that expect a raw pointer as input, and instead of changing all of the function declarations and definitions, I have simply been accessing the raw pointer associated with the std::vector. I.e., code that was:

double *doubleVec = new double[size];
//code that puts values in doubleVec
someFunc(doubleVec);

becomes

std::vector<double> doubleVec(size);
//code that puts values in doubleVec
someFunc(&doubleVec.front());

Is this considered bad practice? On the one hand, I am using a wrapper class and then completely ignoring the wrapper in the function calls, which doesn't really make sense. On the other hand, the point of the wrapper class is to take care of memory management, and since the function calls do not mess with the memory in any way, it's doing it's job.

Best Answer

What you should worry about is ownership of the data and how long the pointers should/will be valid.

Using std::vector will allow you to be more relaxed about validity though you should still be careful as a reallocation will invalidate the pointer.

However much C++ code is littered with &vector[0] to get the pointer to the first element so it's very much accepted to grab a raw pointer to fill in data using a third party library.

Related Topic