Removing objects from C ++ containers without deleting them

I am using a C ++ std vector to store visualization objects for a simple implementation of scene graphics. I need the ability to add and remove render objects at runtime from the scene graph. Adding is not a problem to delete: reading documents for vector and other C ++ containers, it seems that when objects slipped out, their destructors are called. This is not what I need, because I want to be able to re-add these objects later in the render loop. What is the possible solution to this problem? Important detail I forgot to mention - I use a vector of pointers to rendering objects.

+4
source share
3 answers

You seem to be confused with the basic concept of object instances. When you add something to a vector, you do not move it into it, you copy it:

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

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

If you do not want to copy, you should switch to pointers. You can remove pointers from a vector, and the destructor of the object they point to will not be called.

Edit: Well, it looks like you are already using pointers. You said:

reading documents for vector and other containers in C ++ shows that when objects popped up, their destructors are called

It's right. When you remove a pointer from a vector, the pointer becomes destroyed. This is what documents mean. This does not mean that the object pointed to by the pointer is destroyed:

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

s is not affected at all. What is destroyed by the pop operation is a pointer that contains the address s , not s .

So, you are fine.

+7
source

You need to know about the property in order to do this job correctly. If the vector you are using is temporary and only for observing objects, just use the point vector.

 std::vector<object*> x; 

When this vector destroyed, the objects pointed to are not affected.

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

+3
source

When a pointer is called, the call to the destructor is not called. It is understood that even primitive types have destructors to explain what happens when they go beyond. Destroying the pointer vector coincides with the fact that the presence of several pointer variables goes beyond the scope.

Reference counting smart pointers are objects that overload the * and -> operators to behave like pointers. They implement a destructor to destroy the directed object, thereby realizing the right of ownership. But for the scene graph, this is probably not necessary.

+2
source

All Articles