Click here to Skip to main content
15,893,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a pointer in my main function;
C++
Something* myptr = new Something();

I then add it a std::vector with push_back;
C++
std::vector<Something*> vec;
vec.push_back(myptr);

I then want to delete it from that vector without destroying it, because the main function still needs it. Essentially I'm removing one reference to it from the vector.

How can I achieve this?

What I have tried:

C++
vec.erase(std::remove(vec.begin(), vec.end(), myptr), vec.end());
C++
vec.erase(std::remove(vec.begin(), vec.end(), &myptr), vec.end());
C++
vec.erase(myptr);
C++
delete vec[myptr];
Posted
Updated 21-Jun-22 4:42am
v2

You could also use a std::shared_ptr, instead of a naked pointer.
 
Share this answer
 
Comments
Greg Utas 21-Jun-22 11:29am    
5. And then the number of users of the pointer would be decremented when it was erased.
CPallini 21-Jun-22 13:01pm    
Thank you.
Given your code above, this will remove an element from the vector which equals to your pointer without deleting is so to speak. The pointer itself must be deleted in a separate step.

C++
std::vector<Something*>::iterator it = std::find(vec.begin(), vec.end(), myptr);
if(it != vec.end())
   vec.erase(it);
 
Share this answer
 
v2
Comments
CPallini 21-Jun-22 10:41am    
5.
sorauts 21-Jun-22 11:20am    
Thank you - just needed an #include <algorithm> and it's working great

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900