我创建了一个指向 double 组的指针 vector 。这些指针在函数(即 InsertIntoVector
)退出后有效吗?如果我稍后像在 GetVecElement
中那样获取指针,是否仍然保证指针指向它们被分配的同一内存位置?
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];
}
最佳答案
那些不是引用!那些是指针...
If I later fetch the pointer as in GetVecElement, are the references still guaranteed to point to the same memory location they were assigned?
您没有删除指针,std::vector
不会为您做这件事,所以是的,指针将保持有效。它也将被泄露,除非您在A
的析构函数中手动删除
它们中的每一个。但是为此,您还需要一个复制构造函数 和一个赋值运算符,以克隆vector
的内容。
关于c++ - 将引用插入 vector ,函数退出后引用是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10957271/