【发布时间】:2018-08-18 16:09:06
【问题描述】:
我试图掌握 C++ 中的指针,但我找不到这些问题的答案。
如果我在 Java 中有一个 ArrayList,并且我想在循环中向它添加新对象,我会执行以下操作:
ArrayList<MyObject> list = new ArrayList<MyObject> ();
for (int i = 0; i < otherList.length; i++) {
list.add(i, new MyObject(otherList.get(i)));
}
但是假设我想在 C++ 中使用向量做同样的事情。我找到了两种方法:
vector<MyObject> vector;
for (auto i = otherVector.begin(); i != otherVector.end(); i++) {
// do this
vector[i - otherVector.begin()] = * new MyObject(*i);
// or this
MyObject newObj(*i);
vector[i - otherVector.begin()] = newObj;
}
这两种方法有什么区别,如果我使用第二种方法,是否需要手动从列表中删除指针?如果我将第二种方法与智能指针一起使用,当向量不再使用时,它们会被 gc 自动删除吗?
【问题讨论】:
标签: c++ pointers vector stdvector