What will happen if a std::vector element 'com

2019-04-01 12:54发布

Suppose there's a vector of Items

vector<Item*> items; //{item1, item2, item3}

Then, in other part of the code,

items[1]->suicide();

where the suicide function is:

void Item::suicide()
{
   delete this;
}

What is items vector size and how it's arrangement now? It is okay to do this?

Edit (may I ask an additional question?): If the desired arrangement of the output is {item1, item3}, size is 2, and no dangling pointer, how to do it in a self-destructing way (from the item2 itself)?

Edit 2 : Thanks for all the answers! Awesome. So I finally decided and found the way to do it from outside of the object because it was a bad practice and unnecessarily complicated

7条回答
ゆ 、 Hurt°
2楼-- · 2019-04-01 13:39

That's ok in case of vector of pointers as vector will not call Item's destructor. But you have to somehow know which pointers are still valid.

If you are storing Items in vector by value, calling Item's destructor is not ok. When vector will be destroyed or cleared, it will call item's destructor again, causing application crash.

查看更多
登录 后发表回答