【发布时间】:2021-06-20 12:48:20
【问题描述】:
我已经编写了以下代码来放置 new 和 delete 运算符函数。能否请您用下面的代码说明问题。
// new_operator.cpp : This file contains the 'main' function. Program execution begins and ends there.
//
#include <iostream>
using namespace std;
class Mem
{
public:
void* alloc(size_t sz) { return malloc(sz); }
void dealloc(void* ptr) { free(ptr); }
};
class Object
{
public:
Object() { cout << "In Constructor Object()" << this << endl; }
~Object() { cout << "In Destuctor ~Object()" << endl; }
void* operator new(size_t sz, Mem* handle)
{
Object* x1 = (Object*)handle->alloc(sz);
return x1;
}
void operator delete(void* ptr, Mem* handle)
{
cout << "Here\n";
((Object*)(ptr))->~Object();
handle->dealloc(ptr);
}
};
int main()
{
Mem* memory = new Mem;
Object* obj = new (memory) Object;
cout << "Obj is " << obj << endl;
delete (obj, memory);
delete memory;
return 0;
}
在删除运算符函数开始执行时,我遇到了运行时崩溃。谁能告诉我做错了什么。
【问题讨论】:
-
你认为这是做什么的?
(obj, memory) -
为什么要在分配给
Mem的空间中存储Object? -
在
delete (obj, memory);中,您正在调用comma operator,因此该语句实际上与delete memory;相同,您随后也会立即调用。因此,您delete使用相同的memory两次。此外,您不能delete使用placement-new创建的对象,因为它会尝试释放未使用new分配的内存。 -
@DavidC.Rankin
operator new函数分配字节,而不是对象。 -
@DavidC.Rankin 不,
operator new的成员版本仍然分配原始字节。它不应该构造任何类对象。malloc就好了。
标签: c++ operator-overloading dynamic-memory-allocation new-operator delete-operator