Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/138.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 具有析构函数和新运算符的类;_C++_Overloading_Destructor_Operator Keyword - Fatal编程技术网

C++ 具有析构函数和新运算符的类;

C++ 具有析构函数和新运算符的类;,c++,overloading,destructor,operator-keyword,C++,Overloading,Destructor,Operator Keyword,我用下面的代码重载了新操作符 void* operator new(size_t size) { cout<<"size=>"<<size<<endl; return malloc(size); } 我写了以下声明 c * p=new c; // gives me the output size=>1 OK Fine.. c *p=new c[100]; // gives me the output size => 100

我用下面的代码重载了新操作符

void* operator new(size_t size)
{
    cout<<"size=>"<<size<<endl;
    return malloc(size);
}
我写了以下声明

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位操作系统,所以我猜每次都会分配一个额外的指针)


当类中有析构函数时,为什么我的编译器要分配这个额外的指针(如果是其他指针的话)?

您不必担心这种行为,因为它是实现定义的

在您的特定情况下,编译器存储有关数组大小的信息,以便在调用析构函数时知道存储了多少个元素

对于POD结构,它并没有任何非平凡的析构函数,编译器不会调用它,所以它不需要关于数组大小的信息。8可能是
sizeof(size\u t)
,因为您可以在数组中存储
size\u t
元素


同样,所有这些都是实现定义的,只是推测。

还要注意,您错误地重载了
操作符new
。如果分配错误,它应该抛出
std::bad_alloc
,而不返回0。对于数组,它应该是
operator new[]
c *p= new c;// gives me the output size=>1 OK Fine..
c *p=new c[100]; // gives me the output size => 108.