7

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.

  • 5
    C++11 has vector::data() member so you don't need to &front. – ratchet freak Jan 6 '15 at 15:20
  • @ratchetfreak: Unfortunately, I don't have access to C++11, though the existence of that function appears to make the question moot. Clearly, it's not bad practice if the standard explicitly makes allowance for it. – wolfPack88 Jan 6 '15 at 15:22
  • 4
    @wolfPack88: To my knowledge, the omission of vector::data() was considered an oversight. You might check if your implementations support it despite not being C++11 compliant. – Bart van Ingen Schenau Jan 6 '15 at 15:24
8

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.

8

There's now a vector.data() method which explicitly blesses the practice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.