I am having trouble understanding how the C++ std::vector container would get freed in the following scenario
void DoSomething()
{
cv::Point ** curves;
int * curve_sizes;
num_curves = m_curves.size(); //member variable holdings curves
curves = new cv::Point*[num_curves];
curve_size = new int[num_curves];
std::vector<cv::Point> cur_points;
for(int i = 0; i < num_curves; ++i)
{
cur_points = CreatePolyPoints(m_curves[i]);
curves[i] = &cur_points[0];
curve_sizes = cur_points.size();
}
cv::fillPoly(m_roi, curves, curve_sizes, num_curves, ... );
//Clear the dynamic data
// Do i do aything here?
delete [] curves;
delete [] curve_sizes;
}
std::vector<cv::Point> CreatePolyPoints(Curve curve)
{
std::vector<cv::Point> points;
//Do work here here
while(something)
{
cv::Point cur_point;
points.push_back(cur_point);
}
return points;
}
Thanks in advance. If anyone is interested in my goal: Generate an ROI given polygons defined by “n” curves.
It is not dynamically allocated so it will be destroyed as soon as it goes out of scope. In your case, your variable will go out of scope after the
DoSomething()function exits. Your local variablecur_pointsgets the return value ofCreatePolyPoints()assigned to it within your loop. When this happens, the old contents ofcur_pointswill no longer exist – you do not need to worry about this, as the instances ofCurveobjects within that vector will get destroyed each time the vector gets reassigned. Similarly whencur_pointsgoes out of scope.EDIT: You do seem to have a problem here
You assign the address of the vector element 0 to your
ithelement ofcurvesat each iteration – The problem here is that that will be the address of an object that no longer exists. This is because the contents of the vector will no longer exist oncecur_pointsgets reassigned next time in the loop iteration, therefore the pointers you are storing do not point to valid objects – they point to objects that have been destroyed already. When your loop finished, the vector will contain the contents returned in the last call toCreatePolyPoints. If you want to make sure that all thecv::Pointobjects still exist at the point you callcv::fillPolyyou should consider passing the vector by reference to theCreatePolyPoints()function rather than return a new vector by value each time. This will ensure that ALL items you add viaCreatePolyPointswill still exist once your loop finishes