我试图掌握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会自动删除它们吗?
答案 0 :(得分:2)
第一种方法会造成内存泄漏。没有保存它。忘记你曾经听说过算子new
。
如果我使用第二个,我是否需要手动删除列表中的指针?
列表中没有指针。
第二个会工作,当vector
超出范围时,它会自行清理。但是也不要这样做。
vector<MyObject> vector;
for (auto i = otherVector.begin(); i != otherVector.end(); i++) {
// do this
vector[i - otherVector.begin()] = * new MyObject(*i); // No, no, no, no.
// or this
MyObject newObj(*i);
vector[i - otherVector.begin()] = newObj; // Please don't.
}
但这是应该做的一种方式。没有循环。 (并且不要将事物命名为“矢量”。)
std::vector<my_object> vec(other_vector);
如果你真的喜欢简洁的话,那就去做吧:
auto vec{other_vector};