c++ - 将引用插入 vector ,函数退出后引用是否有效?

标签 c++ memory-management memory-leaks

我创建了一个指向 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/

相关文章:

c++ - 将具有多个空格的字符串添加到文本文件

c++ - Win32 消息泵与 MFC 消息映射,哪个更快? C++

c - 如何正确安全地 free() 所有内存使用 C 中的嵌套结构?

c# - 每次加载新的 JQuery 插件 DataTables 时都会加载更改事件导致内存泄漏

c++ - 如何将函数作为 cuda 内核参数传递?

c++ - 了解缓存友好、面向数据的对象和句柄

c - pthreads 中的段错误,Linux Ubuntu

linux - smem如何计算RSS、USS和PSS?

c# - 内存泄漏: ListView with Bitmaps

条件跳转或移动取决于 C 中未初始化的值