简体   繁体   English

未调用指针数组的 C++ 重载删除运算符

[英]C++ overloaded delete operator for array of pointers not being called

The delete operator is not being called.未调用删除运算符。 Any direction would be helpful.任何方向都会有所帮助。 I am using Visual studio 2019. I did look at the link overload delete[] for array of pointers , but was not able to resolve my issue.我正在使用 Visual Studio 2019。我确实查看了指针数组的链接重载 delete[] ,但无法解决我的问题。 Thank you for any help!感谢您的任何帮助!

#include <cstdio>
#include <cstdlib>
#include <new>
// replacement of a minimal set of functions:
void* operator new(std::size_t sz) // no inline, required by [replacement.functions]/3
{
   std::printf("global op new called, size = %zu\n", sz);
   if (sz == 0)
      ++sz; // avoid std::malloc(0) which may return nullptr on success

   if (void* ptr = std::malloc(sz))
      return ptr;

   throw std::bad_alloc{}; // required by [new.delete.single]/3
}
void operator delete(void* ptr, size_t size) noexcept
{
   std::puts("global op delete called");
   std::printf("%d", size);
   std::free(ptr);
}
void operator delete[](void* ptr, size_t size) noexcept
{
   std::puts("global op delete called");
   std::printf("%d", size);
   std::free(ptr);
}
int main()
{
   unsigned char* p3 = new unsigned char[100]; 
   delete[] p3; // I was expecting this would call the overloaded delete operator
   return 0;
}


You're not providing an overload for operator new[](size_t sz) , so you're lucky that your operator new(size_t sz) is being called at all.您没有为operator new[](size_t sz)提供重载,因此您很幸运,您的operator new(size_t sz)正在被调用。

The compiler is calling the unsized versions delete[] , so you need to provide a operator delete[](void *ptr) noexcept function.编译器正在调用 unsized 版本delete[] ,因此您需要提供operator delete[](void *ptr) noexcept函数。 Note that the standard requires the non-size version to be replaced when replacing the version that takes a size.请注意,标准要求在更换需要尺寸的版本时替换非尺寸版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM