【发布时间】:2020-05-18 21:14:11
【问题描述】:
我有以下课程:
#include <iostream>
#include <math.h>
#include <vector>
class minimal
{
private:
int x;
int y;
public:
minimal(int x = NAN, int y = NAN) // default constructor
{
this->x = x;
this->y = y;
}
~minimal(){}
void setvals(int xin, int yin)
{
this->x = xin;
this->y = yin;
}
int getx() {return this->x;}
};
int main() {
// goal: create a vector of type minimal to be located in the heap
std::vector<minimal*> vectinheap;
minimal * min_ptr = new minimal;
for (int i = 0; i < 4; ++i)
{
min_ptr->setvals(i, -i);
vectinheap.push_back(min_ptr); // send a local copy to vectinheap?
}
delete min_ptr; // free the heap
min_ptr = nullptr; // free dangling pointer
// now how to iterate through vect in heap.. ?
return 0;
}
由此引发了几个问题:
- 当我说
vectinheap.push_back(min_ptr)时,是要使向量中的每个值最终都指向同一个实例,还是会像我想要的那样附加当前实例? - 加载位于堆中的向量后,如何通过索引向量来遍历和访问每个实例?
【问题讨论】:
-
您能否将显示的代码缩减为minimal reproducible example?我的印象是不需要所有的课程细节。你能用简单的整数代替这个问题吗?例如。在
main()内将所有minimal替换为整数,将min_ptr->setvals(xlocal, ylocal);替换为*min_ptr = i;。我想你会意识到你的问题的答案。 -
你知道让多个指针指向同一个对象和创建新对象的区别吗?
-
@Yunnosch 我不知道如何在不完全回答我的问题的情况下使它变得更小。它都位于
main.cpp我应该休息一下吗?我的目标不是让多个指针指向同一个对象(参见问题 1)。 -
首先在向量中存储
minimal*而不是minimal有什么意义? -
@AlexanderHuszagh 是的,感谢您的洞察力。非常有帮助。这是个好地方。
标签: c++ object vector heap-memory