在对象向量中添加指针
Adding a pointer in a vector of objects
我正在尝试掌握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;
}
这两种方法有什么区别,如果我使用第二种方法,是否需要手动从列表中删除指针?如果我对智能指针使用第二种方法,当不再使用 vector 时它们会被 gc 自动删除吗?
第一种方法会造成内存泄漏。没救了。忘记你曾经听说过运算符 new
.
if I use the second one, do I need to manually delete the pointers from the list?
列表中没有指针。
第二个可以工作,当 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.
}
但这是应该完成的一种方法。没有循环。 (并且不要命名事物 "vector"。)
std::vector<my_object> vec(other_vector);
如果您真的很喜欢简洁,请执行以下操作:
auto vec{other_vector};
我正在尝试掌握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;
}
这两种方法有什么区别,如果我使用第二种方法,是否需要手动从列表中删除指针?如果我对智能指针使用第二种方法,当不再使用 vector 时它们会被 gc 自动删除吗?
第一种方法会造成内存泄漏。没救了。忘记你曾经听说过运算符 new
.
if I use the second one, do I need to manually delete the pointers from the list?
列表中没有指针。
第二个可以工作,当 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.
}
但这是应该完成的一种方法。没有循环。 (并且不要命名事物 "vector"。)
std::vector<my_object> vec(other_vector);
如果您真的很喜欢简洁,请执行以下操作:
auto vec{other_vector};