如何理解new运算符重载?

How to understand new operator overloading?

对于"+"运算符重载,还是比较容易理解的。 c = c1.operator+(c2)是函数符号,c = c1 + c2是运算符符号。
但是,我就是无法理解 new 运算符重载。在以下代码中:
请告诉我在处理 student * p = new student("Yash", 24); 时发生了什么 为什么 void * operator new(size_t size) 被调用。还有为什么输入operator new(size_t size)时size是28

// CPP program to demonstrate 
// Overloading new and delete operator 
// for a specific class 
#include<iostream> 
#include<stdlib.h> 

using namespace std; 
class student 
{ 
    string name; 
    int age; 
public: 
    student() 
    { 
        cout<< "Constructor is called\n" ; 
    } 
    student(string name, int age) 
    { 
        this->name = name; 
        this->age = age; 
    } 
    void display() 
    { 
        cout<< "Name:" << name << endl; 
        cout<< "Age:" << age << endl; 
    } 
    void * operator new(size_t size) 
    { 
        cout<< "Overloading new operator with size: " << size << endl; 
        void * p = ::new student(); 
        //void * p = malloc(size); will also work fine 
    
        return p; 
    } 

    void operator delete(void * p) 
    { 
        cout<< "Overloading delete operator " << endl; 
        free(p); 
    } 
}; 

int main() 
{ 
    student * p = new student("Yash", 24); 

    p->display(); 
    delete p; 
} 

中的参数
student * p = new student("Yash", 24);

student 构造函数的参数,它们不会传递给 operator new,后者的唯一职责是为 student 对象分配足够的内存。

为了给student对象分配足够的内存,必须告诉operator new它需要分配多少内存,这就是28,它的值sizeof(student).

所以你的代码

void * operator new(size_t size) 
{ 
    cout<< "Overloading new operator with size: " << size << endl; 
    void * p = ::new student(); 
    //void * p = malloc(size); will also work fine 

    return p; 
} 

实际上是不正确的,因为您正在创建一个不属于 operator new 责任的 student 对象。但是,使用 malloc 的注释掉的代码是正确的。

要查看此问题,您应该添加以下内容

student(string name, int age) 
{ 
    cout<< "Constructor is called with " << name << " and " << age "\n" ; 
    this->name = name; 
    this->age = age; 
} 

现在你会看到你的错误版本为一个对象调用了两个构造函数。这是因为您错误地从 operator new.

调用了构造函数

可以将用户代码中的任意值显式传递给 operator new。如果您想对此进行调查,请查看 placement new.