Par*_*aAi 0 c++ operator-overloading new-operator delete-operator
我创建了一个类并重载了new和delete运算符来打印分配/释放的内存大小。在下面的示例中,它分配了 28 个字节,但释放了 4 个字节。为什么?
#include <iostream>
#include <string>
using namespace std;
class Person
{
private:
string name;
int age;
public:
Person() {
cout << "Constructor is called.\n";
}
Person(string name, int age) {
this->name = name;
this->age = age;
}
void* operator new(size_t size) {
void* p = malloc(size);
cout << "Allocate " << size << " bytes.\n";
return p;
}
void operator delete(void* p) {
free(p);
cout << "Free " << sizeof(p) << " bytes.\n";
}
};
int main()
{
Person* p = new Person("John", 19);
delete p;
}
Run Code Online (Sandbox Code Playgroud)
输出:
Allocate 28 bytes.
Free 4 bytes.
Run Code Online (Sandbox Code Playgroud)
sizeof(p)是 的大小void*,指向 的指针的大小void。它不是该指针所指向的内存块的大小,即sizeof(Person)。
Avoid*本身不携带有关被指者尺寸的信息。不过,在后台free“知道”关联的内存块有多大p,因为您在使用时指定了大小malloc。如果您要实现自己的内存管理而不是回退到free/ malloc(例如,您可以使用使用一些预分配内存的大块的内存池),那么您还需要实现从指针到内存块大小的映射。