Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing objects from C++ containers without deleting them

I am using C++ std vector to store render objects for a simple scene graph implementation.I need an ability to add and remove render objects in run time from the scene graph.Adding is not a problem,for removing: reading docs for vector and other C++ containers it appears that when objects are popped their destructors are called.That is not what I need because I want to be able to re-add those objects later to the rendering loop.What are the possible solution to this problem? Important detail I forgot to mention -I am using vector of pointers to the render objects.

like image 620
Michael IV Avatar asked Nov 25 '12 10:11

Michael IV


2 Answers

It seems you're confused with the basic concept of object instances. When you add something to a vector, you don't move it into it, you copy it:

vector<string> vec;
string s;
vec.push_back(s);

vec[0] is not s, it's a copy of s. So when you remove it from the vector, s is not affected.

If you don't want copies, you should switch to pointers instead. You can them remove the pointers from the vector and the destructor of the object they point to will not be called.

Edit: OK, it seems you're already using pointers. You said:

reading docs for vector and other C++ containers it appears that when objects are popped their destructors are called

That is true. When you remove a pointer from the vector, the pointer is getting destroyed. That's what the docs mean. It doesn't mean that the object the pointer points to is getting destroyed:

vector<string*> vec;
string s;
vec.push_back(&s);
vec.pop_back();

s is not affected at all. What gets destroyed by the pop operation is the pointer that holds the address of s, not s itself.

So you're fine.

like image 98
Nikos C. Avatar answered Sep 21 '22 11:09

Nikos C.


You need to be aware of ownership to make this work correctly. If the vector you are using is only temporary and only to observe objects, just use a vector of points.

std::vector<object*> x;

On destruction of that vector the objects that are being pointed to are unaffected.

If you want to share ownership, use a boost::shared_ptr or std::shared_ptr.

like image 39
pmr Avatar answered Sep 21 '22 11:09

pmr