简体   繁体   中英

C++: What is the proper way to remove elements from a vector of object pointers without deleting the object it points to?

What is the proper way to remove elements from a vector of object pointers without deleting the object it points to?

I am trying to selectively remove elements from my vector

std::vector<Node*>openNodes;

without destroying any of the Node objects being pointed to. (Those nodes are being used elsewhere.)

I tried using < algorithm >'s remove_if function like so

std::remove_if(openNodes.begin(),openNodes.end(),CheckClosedNode);

using my own custom comparator function

bool CheckClosedNode(Node *tocheck)
{
    if(tocheck->isOpen)
        return false; //Don't remove. Node is still open.
    else
    {
        //std::cout << "node " << tocheck->id << " is being removed from open list..." << std::endl;
        return true; // Remove. Node is closed.
    }
}

However, when I std::cout the contents of openNodes, nothing has been removed. I read that I ought to use std::erase() in conjunction with remove_if(), but erase() will delete the nodes. I thought of moving all elements that needed to be removed to the front of the vector and doing a pop_front(), but turns out that pop_front also deletes.

Is there a standard way to remove elements from a vector without deleting the object?

It actually won't delete the nodes if they are pointers. When you allocate memory for an object using new it is your job to delete the pointer. Now if you had declared it like vector<Node> this would be an issue since erase would have to call the deconstructor on Node. However a pointer is really like an int type (since it is just a memory address). When you remove it from a vector nothing happens to the memory it points to.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM