假设我为两个数组分配了内存,一个使用 new
运算符,另一个使用 malloc
函数。据我所知,这两个内存都是在堆段中分配的,那么我的问题是编译器如何知道使用哪个运算符或函数分配了哪个内存?或者这背后有什么其他的概念。
最佳答案
编译器不必知道指针后面的内存是如何分配的,这是程序员的责任。您应该始终使用匹配的分配-解除分配函数/运算符。例如,operator new 可以重载。在这种情况下,当你用 new 分配对象,然后用 free() 释放它时,你就有麻烦了,因为 free() 不知道你在那里有什么样的簿记。下面是这种情况的简化示例:
#include <iostream>
#include <stdlib.h>
struct MyClass
{
// Really dumb allocator.
static void* operator new(size_t s)
{
std::cout << "Allocating MyClass " << s << " bytes.\n";
void* res = Pool + N * sizeof(MyClass);
++N;
return res;
}
// matching operator delete not implemented on purpose.
static char Pool[]; // take memory from this statically allocated array.
static unsigned N; // keep track of allocated objects.
};
char MyClass::Pool[10*sizeof(MyClass)];
unsigned MyClass::N = 0;
int main(int argc, char** argv)
{
MyClass* p = new MyClass();
if (argc == 1)
{
std::cout << "Trying to delete\n";
delete p; // boom - non-matching deallocator used.
}
else
{
std::cout << "Trying to free\n";
free(p); // also boom - non-matching deallocator used.
}
}
如果您混合搭配分配器和释放器,您将遇到类似的问题。
关于c++ - 编译器如何知道使用哪个运算符或函数分配了哪个内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24909711/