【发布时间】:2018-11-01 05:51:32
【问题描述】:
以下代码 sn -p 重载operator new[] 并打印出size 所需的地址和指针地址
class MyClass
{
private:
int _data; //sizeof(MyClass) == 4
public:
void* operator new[](size_t size)
{
cout << "MyClass::operator new[]" << endl;
cout << "size = " << size << endl;
void* p = malloc(size);
cout << "p = " << p << endl;
return p;
}
};
int main()
{
MyClass* a = new MyClass[100];
cout << "a = " << a << endl;
}
输出
>> MyClass::operator new[]
>> size = 400
>> p = 0x55e335a3f280
>> a = 0x55e335a3f280
但是,通过显式添加/定义析构函数
class MyClass
{
...
public:
...
~MyClass() {}
};
int main()
{
MyClass* a = new MyClass[100];
cout << "a = " << a << endl;
}
结果变了
>> MyClass::operator new[]
>> size = 408
>> p = 0x564f30cd7280
>> a = 0x564f30cd7288
意味着表达式new[] 正在向operator new[] 请求额外的8 字节内存。内存的额外字节似乎是存储数组的大小,甚至可以访问!
cout << "info: " << *(reinterpret_cast<size_t*>(a) - 1) << endl;
结果
>> info: 100
我的问题是谁以及为什么使用这 8 个字节的信息?这是标准的一部分吗?如果是这样,有没有解释为什么它被设计成这样?
【问题讨论】:
-
请注意,
new[]表达式正在请求额外的 8 个 字节 内存,而不是 位。 -
糟糕,我会修改帖子。
标签: c++ memory new-operator