答案是不同的new/delete
。new[]/delete[]
您可能不会感到惊讶,但另一个令人惊讶的消息(双关语不是有意的)是该new
运算符并且operator new
是不同的。
这是测试问题的示例代码(您可以更改tested_type
typedef 的内容):
#include <iostream>
#include <vector>
#include <string>
typedef std::string tested_type;
void* Test2;
size_t allocated_mem_size;
void* operator new[] (size_t e)
{
void* retaddr = operator new(e);
Test2 = retaddr;
allocated_mem_size = e;
return retaddr;
}
int _tmain(int argc, _TCHAR* argv[])
{
void* Test1 = new tested_type[10];
std::cout << "sizeof(tested_type)*10 is " << sizeof(tested_type)*10 << "\n"
<< "Test1 is " << Test1 << "\n"
<< "Test2 is " << Test2 << "\n"
<< "operator new[] was called with e == " << allocated_mem_size << "\n"
<< "What's in the missing bytes? " << *(size_t*)Test2 << "\n";
}
我机器上的输出是:
sizeof(tested_type)*10 is 280
Test1 is 0085D64C
Test2 is 0085D648
operator new[] was called with e == 284
What's in the missing bytes? 10
(注意 - 我有一个 32 位编译器)
如果我们更改tested_type
为 int,我们有:
sizeof(tested_type)*10 is 40
Test1 is 0070D648
Test2 is 0070D648
operator new[] was called with e == 40
What's in the missing bytes? 3452816845
现在,如果我们更改tested_type
为std::vector<int>
,我们有
sizeof(tested_type)*10 is 160
Test1 is 004AD64C
Test2 is 004AD648
operator new[] was called with e == 164
What's in the missing bytes? 10
现在我们在这里看到一个模式:添加的额外字节等于分配的元素数量。此外,添加字节的唯一时间是类型不平凡的时候......
而已!
调整地址的原因是new[]
要存储元素的数量。在某些情况下我们需要存储元素数量而在其他情况下不需要存储元素数量的原因是因为delete[]
调用析构函数,并且delete[]
(但不是delete
只为单个元素调用析构函数)必须以某种方式知道它必须销毁多少元素。不需要为基本类型调用析构函数int
,因此new[]
不存储有多少。
(另外,我推荐std::vector
- 它只是工作)