Why is vector deleting destructor being called as a result of a scalar delete?

后端 未结 5 1616
轮回少年
轮回少年 2020-12-31 11:23

I have some code that is crashing in a large system. However, the code essentially boils down to the following pseudo-code. I\'ve removed much of the detail, as I have tried

5条回答
  •  时光说笑
    2020-12-31 11:43

    This behavior is special to MSVC 9, where the delete operator for a exported class, that has a virtual destructor is implicitly generated and mangled to vector dtor with an associated flag, where 1 means (scalar) and 3 means (vector).

    The true problem with this thing is, that it breaks the canonical form of new/delete, where the client coder is not able to disable the vector delete operator in its code, if he thinks, that it is a bad idea to use it.

    Moreover the vector dtor, also seems to be executed wrong, if the new is allocated in another module than the module the implementation resides in and is then hold in a static variable via a reference count, which executes a delete this (here the vector dtor comes into play) on process shutdown.

    This matches to the heap problem 'bshields' already mentioned before, the dtor is executed on the wrong heap and the code crahses either with 'cannot read that memory location' or 'access violation' on shutdown - such problems seem to be very common.

    The only way around this bug, is to forbid the usage of a virtual destructor and execute it your own, by enforcing the usage of a delete_this function from the base class - stupid as it is you imitate the stuff the virtual dtor should do for you. Then also the scalar dtor is executed and on shutdown any ref counted objects shared between modules, can be instantiated in a safe way, because heap is always addressed correctly to the origin module.

    To check, if you have such problems, simply forbid the usage of the vector delete operator.

提交回复
热议问题