小编Par*_*aAi的帖子

为什么重载new和delete运算符时释放的内存小于分配的内存?

我创建了一个类并重载了newdelete运算符来打印分配/释放的内存大小。在下面的示例中,它分配了 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) << " …
Run Code Online (Sandbox Code Playgroud)

c++ operator-overloading new-operator delete-operator

0
推荐指数
1
解决办法
65
查看次数