C-std:: remove in STD:: vector_ if polymorphic std :: unique_ ptr

I have a three - level hierarchy, derived from optional and paintable derivatives Then I have a vector unique_ PTR < drawable > I fill with derived objects

I'm sure the vector can only be filled with objects from two bases at the same time

The problem arises when I try to delete an element from a vector by using a pointer to selected

Obviously, if I choose the drawable pointer, everything is fine, but this is not my intention

I got a runtime error that caused the program to crash Why does this happen and how can I solve it?

Solution

The key issue is STD:: remove_ If how to delete an element:

So basically, you keep one by PTR = VEC [2] Get () gets the original pointer, but there is no guarantee that PTR will remain valid You can only guarantee that VEC [2] is valid (before filtering, the only pointer in VEC [2] is located between the new logical end and the physical end, with an unspecified value)

In your example, when STD:: remove_ When if reaches the third element, the predicate returns true and remove_ If call VEC [2] Destructor for get() Because you keep an original pointer, the pointer you use has been destroyed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>