使用可选参数重载 new 和 delete 运算符
overloading new and delete operator with optional arguments
#include <new>
#include <cstdlib>
#include <iostream>
#include <stdexcept>
struct foo {};
inline void* operator new(size_t size, foo*) throw (std::bad_alloc)
{
std::cout << "my new " << size << std::endl;
return malloc(size);
}
inline void operator delete(void* p, foo*) throw()
{
std::cout << "my delete" << std::endl;
free(p);
}
int main()
{
delete new((foo*)NULL) foo;
}
输出(通过 ideone):
my new 1
我的想法是,C++会释放一个带有附加参数的新对象,并匹配删除相同的参数,但我显然是不正确的。
获取上述代码以调用重载删除的正确方法是什么?
当你使用任何形式的放置新时,除了std::nothrow_t
版本,你需要显式销毁对象,并以你认为合适的任何方式释放它的内存。但是,operator delete()
的重载版本仍然需要存在,因为如果对象的构造引发异常,则会使用它!在这种情况下,不会返回任何指针,因为会引发异常。因此,在这个分配过程中必须摆脱内存。
也就是说,您main()
应该看起来像这样:
int main()
{
foo* p = new (static_cast<foo*>(0)) foo;
p->~foo();
operator delete(p, static_cast<foo*>(0));
}
相关文章:
- new[] / delete[] 并在C++中抛出构造函数/析构函数
- QQuickView new-delete-type-mismatch
- 创建 myNew/myDelete 以替换 new/new[]/delete/delete[]
- 为多线程环境包装 c++ new/delete 的安全/好方法
- c++ 运算符 new[]/delete [] 是否调用运算符 new/delete?
- C++内存分配失败(使用 new & delete)
- c++重载运算符new delete
- 在 C++ 中将 malloc/free 替换为 new/delete
- new/delete 和 ::new/::d elete 有什么区别?
- 我什么时候应该在C++中重载new/delete
- 在C++中,"new/delete"在结构上代替"malloc/free"有多好?
- 为什么我的信号槽比QThreadPool+new+delete慢
- malloc()/free()/new/delete/delete[] 的算法复杂度是多少?
- C++中new[]/delete[]与new/delete之间的差异
- 标准C++的哪些部分将调用malloc/free而不是new/delete
- C++中的 malloc/free 和 new/delete 兼容性
- 编译器将 malloc/free 或 new/delete 对优化为 alloca
- 在 ANSI C 中使用 new/delete 的缺点
- 为什么使用 malloc/free,当我们有 new/delete 时
- c++如何知道在new/delete之后指向内存的位置