c++ - 重载新运算符 : How the size will be passed?

标签 c++ operator-overloading new-operator

我对这段代码有一个疑问:

#include <iostream>
#include <stdlib.h>

using namespace std;
void * operator new(size_t size)
{
    cout << "New operator overloading " <<"\n";
    void * p = malloc(size);
    return p;
}

void operator delete(void * p)
{
    cout << "Delete operator overloading " <<"\n";
    free(p);
}

int main()
{
    int n = 3, i;
    int * p = new int[3];

    for (i = 0; i<n; i++)
    p[i]= i;

    cout << "Array: ";
    for(i = 0; i<n; i++)
    cout << p[i] << " ";

    cout << endl;

    delete p;
}

如何将 int[3] 的大小作为参数传递给 void * operator new(size_t size)

请看下面的代码,这是行不通的:

#include <iostream>

using namespace std;

void sizef(size_t n)
{
    cout<<n;
}

int main()
{
    sizef(int[5]);
}

请解释这是如何工作的。

最佳答案

标准 [expr.new] reads :

A new-expression may obtain storage for the object by calling an allocation function. ... If the allocated type is an array type, the allocation function's name is operator new[] and the deallocation function's name is operator delete[]. ... A C++ program can provide alternative definitions of these functions and/or class-specific versions.

and 1:

new T[5] results in one of the following calls:

  • operator new[](sizeof(T) * 5 + x)
  • operator new[](sizeof(T) * 5 + x, std::align_val_t(alignof(T)))

Here, each instance of x is a non-negative unspecified value representing array allocation overhead; the result of the new-expression will be offset by this amount from the value returned by operator new[]. ... The amount of overhead may vary from one invocation of new to another.


1 请注意,operator new[] 分配存储空间,而不是构造对象。对象构造和初始化是 new 执行的另一部分工作。

关于c++ - 重载新运算符 : How the size will be passed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59245777/

相关文章:

c++ - 在循环内使用 list.push_back(),绕过使迭代器无效

c++ - 并行编程和 C++

java - 如何让这个方法结束递归并达到最大值?

c++运算符<<重载不打印出 vector

c++ - C++中的私有(private)继承以及如何重用但修饰基类的运算符?

C++ 未初始化的类实例数组

c++ - 在非 pod 结构上使用 operator new + Initializer list

c++ - 这里发生溢出了吗?

c++ - Winsock 2 可移植性

c++ - 使用不同的参数重载运算符两次