c++ - 在 nullptr 上使用重载/替换的 delete[]

标签 c++

在 stackoverflow 上搜索后我发现:“检查仍然是操作符 delete(或 delete[])的责任;标准不保证它不会被赋予空指针;标准要求如果给定一个空指针,它就是一个空操作。“(delete a NULL pointer does not call overloaded delete when destructor is written) 现在我的问题是,有什么方法可以强制编译器生成实际调用重载/替换的 delete[](for nullptr) 的代码,例如:

void *operator new[] (size_t n)
{
     std::cout << "new works ";
    return std::malloc (n);
}

void operator delete [] ( void* ptr) {
     if(!ptr) {
          std::cout << "you just tried to delete a nullptr";
          return;
     }
     else {
          std::cout << "delete works";
          free(ptr);
     }
}
int main(){

     char *p(new char[5]);
     char *q = nullptr;
     delete[] p;
     delete[] q;
     return 0;
}

像这样它产生输出:

new works delete works

我试过用 -O0 编译它,但这似乎没有改变任何东西(附加信息:g++ --version g++ (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609 )

最佳答案

标准未指定此行为。

C++11,§5.3.5,第 7 项:

If the value of the operand of the delete-expression is not a null pointer value, the delete-expression will call a deallocation function (3.7.4.2). Otherwise, it is unspecified whether the deallocation function will be called.

C++14 为非空指针的情况添加了一些细节,但空指针的情况是一样的。

如果有任何方法可以强制执行任何特定行为,那就是编译器扩展。

关于c++ - 在 nullptr 上使用重载/替换的 delete[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43504053/

相关文章:

c++ - 在 C++ 中将类型的容器作为字段是个坏主意吗?

c++ - 如何通过 lambda 使用自定义相等性在 std::vector 中查找具有一个匹配元素的元组

IntStack 的 C++ 递归打印函数

c++ - 如何更改子类方法中的参数?

c++ - 如何解析UTF-8中文字符串

c++ - 动态创建包含另一个动态创建的结构数组的结构数组时的内存管理

c++ - 将所有权从 unique_ptr<T,void(*)(T*)> 转移到 unique_ptr<const T,void(*)(const T*)>

c++ - OpenGL 平铺/ block 传输/裁剪

c++ - CUDA C++ : Using a template function which calls a template kernel

c++ - 用 foo(T) 替换模板函数 foo(T*)