我对这段代码有一个疑问:
#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 isoperator 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 byoperator new[]
. ... The amount of overhead may vary from one invocation ofnew
to another.
1 请注意,operator new[]
分配存储空间,而不是构造对象。对象构造和初始化是 new
执行的另一部分工作。
关于c++ - 重载新运算符 : How the size will be passed?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59245777/