I create a vector of pointers to double array. Are these pointers valid after function (i.e. InsertIntoVector) exits? If I later fetch the pointer as in GetVecElement, are the pointers still guaranteed to point to the same memory location they were assigned?
class A {
vector<double*> vec;
void insertIntoVector(double x, double y);
void GetVecElement(int i, double& x, double& y);
};
A::insertIntoVector(double x, double y) {
double* xy = new double[2];
xy[0] = x; xy[1] = y;
vec.push_back(xy);
}
A::GetVecElement(int i, double& x, double& y)
{
x = vec[i][0]; // will the reference to the double array still be valid?
y = vec[i][1];
}
Those are not references! Those are pointers…
You are not deleting the pointer, and
std::vectorwon’t do it for you, so yes the pointers will remain valid. It will also be leaked unless you manuallydeleteeach of them atA‘s destructor. But for that you will need a copy-constructor and an assign-operator as well, to clone the contents of thevector.