【发布时间】:2013-04-28 03:12:48
【问题描述】:
我用下面的代码重载了 new 运算符。
void* operator new(size_t size)
{
cout<<"size=>"<<size<<endl;
return malloc(size);
}
现在,我尝试使用这个重载的new 为类对象分配内存。
假设类体定义为:
class c
{
char ch;
};
我写了以下语句
c * p=new c; // gives me the output size=>1 OK Fine..
c *p=new c[100]; // gives me the output size => 100 OK fine.
但现在我在类中添加了一个析构函数。 所以新的身体变成了:
class c
{
char ch;
public:
~c(){}
};
现在我又写了同样的语句
c *p= new c;// gives me the output size=>1 OK Fine..
c *p=new c[100]; // gives me the output size => 108.
这额外的 8 是从哪里来的?
我尝试使用相同的语句再次分配数组,但我再次得到了 108 的大小。(我有一个 64 位操作系统,所以我猜每次都会分配一个额外的指针)。
当我们在类中有析构函数时,为什么我的编译器会分配这个额外的指针,或者如果它是其他指针?
【问题讨论】:
-
另请注意,您错误地重载了
operator new。它应该在分配错误的情况下抛出std::bad_alloc,而不是返回0。对于数组,它应该是operator new[]。
标签: c++ overloading destructor operator-keyword