why is a scalar deleting destructor being called as a result of vector delete on Windows?

前端 未结 5 1639
时光说笑
时光说笑 2021-01-05 16:56

I have a code that is leaking on Windows. It runs fine on many unix platforms and the leak only occurs on Windows. The binary consists of exe, 1 dll and 2 static libs. The e

相关标签:
5条回答
  • 2021-01-05 17:43

    In general I'd recommend using a std::vector<ClassFromDLL> instead of ClassFromDLL*. Construct it passing in size. Deletion will then be automatic. Unfortunately I don't have much experience with delete[], because I always let the standard library do that for me ;-)

    0 讨论(0)
  • 2021-01-05 17:44

    This is an old Problem in VC++ regarding DLLs and Object-Arrays. The cause is an incorrect compiler optimization as explained by Microsoft.

    http://support.microsoft.com/kb/121216/en-us

    Better use the STL-containers which dont have the problem due to the use of allocator.

    0 讨论(0)
  • 2021-01-05 17:44

    A class in a DLL is extremely touchy, without much help from compilers. Check out this answer for details WHY this is problematic: How can I call a function of a C++ DLL that accepts a parameter of type stringstream from C#?.

    Short version: if the class interface uses ANY inlined code, you will experience potential problems exactly like this. Any templated object (such as std::string) included.

    I would guess this is why. It is similar to the problem @Mikael Persson suggests.

    0 讨论(0)
  • 2021-01-05 17:49

    I think this is a clear case of allocating on one heap and deleting on another (remember that the delete[] has to query the heap for the number of elements in the array, and if the heap does not even contain this pointer, it will return "error" (not really) and it will be assumed that it is just one element and use the scalar delete instead). I think that the problem you have was lost in trying to boil it down to a simple example code. I would suggest you read this article (it's old, but the deletion technique is still very relevant, I use a variation of that technique myself and it works like a charm). One modern way to do this is to attach a deletion function pointer to a smart pointer (shared_ptr) that handles your object, this way, by assigning this deletion function pointer at the same time as you create the object in a factory function, you ensure that the delete will be called on the same heap that it was allocated from.

    0 讨论(0)
  • 2021-01-05 17:51

    Peeking at the code, I'd assume the object was copied by the default copy ctor, which leads to a double-deletion bug. This is Undefined Behavior. It may appear to work, but break due to seemingly unrelated changes - such as switching from a LIB to a DLL.

    0 讨论(0)
提交回复
热议问题