哪个新运算符将被称为 new 或 new[]?
which new operator will be called new or new[]?
在下面的程序中,重载 operator new []
被调用。但是,如果我评论这个函数,那么我的重载 operator new
就会被调用。它不应该调用 default new []
运算符吗?
#include <iostream>
#include <stdlib.h>
using namespace std;
void *operator new (size_t os)
{
cout<<"size : "<<os<<endl;
void *t;
t=malloc(os);
if (t==NULL)
{}
return (t);
}
//! Comment This below function
void* operator new[](size_t size){
void* p;
cout << "In overloaded new[]" << endl;
p = malloc(size);
cout << "size :" << size << endl;
if(!p){
}
return p;
}
void operator delete(void *ss) {free(ss);}
int main ()
{
int *t=new int[10];
delete t;
}
它们之间只有一处不同。使用 "new" 关键字,它只分配原始内存。结果是在该内存中创建了一个真实的活动对象。如果您不调用您的函数,new 将被常规调用。
查看 the reference,我们看到:
void* operator new ( std::size_t count );
Called by non-array new-expressions to allocate storage required for a single object. […]
void* operator new[]( std::size_t count );
Called by the array form of new[]
-expressions to allocate all storage required for an array (including possible new-expression overhead). The standard library implementation calls version (1)
因此,如果您重载版本 (1) 但 不 重载版本 (2),您的行
int *t = new int[10];
将调用标准库的 operator new []
。但是,这又会调用 operator new(size_t)
,你已经超载了。
operator new
被 operator new[]
调用
https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/new_opv.cc#L32
在下面的程序中,重载 operator new []
被调用。但是,如果我评论这个函数,那么我的重载 operator new
就会被调用。它不应该调用 default new []
运算符吗?
#include <iostream>
#include <stdlib.h>
using namespace std;
void *operator new (size_t os)
{
cout<<"size : "<<os<<endl;
void *t;
t=malloc(os);
if (t==NULL)
{}
return (t);
}
//! Comment This below function
void* operator new[](size_t size){
void* p;
cout << "In overloaded new[]" << endl;
p = malloc(size);
cout << "size :" << size << endl;
if(!p){
}
return p;
}
void operator delete(void *ss) {free(ss);}
int main ()
{
int *t=new int[10];
delete t;
}
它们之间只有一处不同。使用 "new" 关键字,它只分配原始内存。结果是在该内存中创建了一个真实的活动对象。如果您不调用您的函数,new 将被常规调用。
查看 the reference,我们看到:
void* operator new ( std::size_t count );
Called by non-array new-expressions to allocate storage required for a single object. […]
void* operator new[]( std::size_t count );
Called by the array form ofnew[]
-expressions to allocate all storage required for an array (including possible new-expression overhead). The standard library implementation calls version (1)
因此,如果您重载版本 (1) 但 不 重载版本 (2),您的行
int *t = new int[10];
将调用标准库的 operator new []
。但是,这又会调用 operator new(size_t)
,你已经超载了。
operator new
被 operator new[]
https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/new_opv.cc#L32