当创建一个新对象时,使用操作符 new 函数分配内存,然后调用构造函数来初始化内存。 这里,new 操作符同时进行分配和初始化,而操作符 new 只进行分配。
让我们看看它们是如何单独工作的。

new 操作符是一个操作符,它表示在堆上分配内存的请求。 如果有足够的内存可用,new 操作符会初始化内存并将新分配和初始化的内存的地址返回给指针变量。 当使用 new 关键字(普通新)创建类对象时。

  • 对象的内存是使用堆中的操作符 new 分配的。
  • 调用类的构造函数以正确初始化此内存。
// CPP program to illustrate
// use of new keyword
#include<iostream>
using namespace std;
class car
{
    string name;
    int num;

    public:
        car(string a, int n)
        {
            cout << "Constructor called" << endl;
            this ->name = a;
            this ->num = n;
        }

        void enter()
        {
            cin>>name;
            cin>>num;
        }

        void display()
        {
            cout << "Name: " << name << endl;
            cout << "Num: " << num << endl;
        }
};

int main()
{
    // Using new keyword
    car *p = new car("Honda", 2025);
    p->display();
}

运行结果:

Constructor called
Name: Honda
Num: 2025

运算符 new

运算符 new 是一个分配原始内存的函数,在概念上有点类似于 malloc()

  • 它是覆盖默认堆分配逻辑的机制。
  • 它不初始化内存,即不调用构造函数。 但是在重载的 new 返回之后,编译器会自动调用构造函数(如果适用)。
  • 也可以全局或为特定类重载运算符 new
// CPP program to illustrate
// use of operator new
#include<iostream>
#include<stdlib.h>

using namespace std;

class car
{
    string name;
    int num;

    public:

        car(string a, int n)
        {
            cout << "Constructor called" << endl;
            this->name = a;
            this->num = n;
        }

        void display()
        {
            cout << "Name: " << name << endl;
            cout << "Num: " << num << endl;
        }

        void *operator new(size_t size)
        {
            cout << "new operator overloaded" << endl;
            void *p = malloc(size);
            return p;
        }

        void operator delete(void *ptr)
        {
            cout << "delete operator overloaded" << endl;
            free(ptr);
        }
};

int main()
{
    car *p = new car("HYUNDAI", 2024);
    p->display();
    delete p;
}

运行结果:

new operator overloaded
Constructor called
Name:HYUNDAI
Num:2024
delete operator overloaded

new运算符

  • 运算符与函数:new 既是运算符又是关键字,而运算符 new 只是一个函数。
  • new 调用“运算符new”:“new运算符”调用“运算符new()”,就像 + 运算符调用运算符 +()
  • “运算符new”可以被重载:运算符 new 可以被重载,就像函数允许执行自定义任务一样。
  • 内存分配:‘new表达式’调用‘运算符new’分配原始内存,然后调用构造函数。