gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:09:52 25 4
gpt4 key购买 nike

在 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++ --versiong++ (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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com