1

I am trying to grasp the pointers in C++ but I can't find the answer to these questions.

If I was to have an ArrayList in Java and I wanted to add new Objects to it in a loop I would do something like:

ArrayList<MyObject> list = new ArrayList<MyObject> ();

for (int i = 0; i < otherList.length; i++) {
    list.add(i, new MyObject(otherList.get(i)));
}

But let's say I wanted to do the same thing in C++ using vectors. I have found two methods:

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;
}

What is the difference between those 2 methods and if I use the second one, do I need to manually delete the pointers from the list? If I were to use the second method with smart pointers, would they be automatically deleted by the gc when the vector was not used anymore?

1 Answer 1

2

The first method creates a memory leak. There's no saving it. Forget you ever heard of operator new.

if I use the second one, do I need to manually delete the pointers from the list?

There are no pointers in the list.

The second would work, and it would clean up after itself when vectorgoes out of scope. But do not do that either.

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.
}

But here's one way it should be done. No loop. (And don't name things "vector".)

std::vector<my_object> vec(other_vector);

If you're really into the brevity thing, do this:

auto vec{other_vector};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.