有没有办法知道指针变量的内存是使用new
还是malloc
分配的?我可以测试一个变量是使用new还是malloc分配的?
int* a = new int;
int* b = static_cast<int*>(malloc(sizeof *b));
//Maybe using a function?
allocatedwithnew(a); //Returns true
allocatedwithmalloc(b); //Return true
有没有办法知道指针变量的内存是使用new
还是malloc
分配的?我可以测试一个变量是使用new还是malloc分配的?
int* a = new int;
int* b = static_cast<int*>(malloc(sizeof *b));
//Maybe using a function?
allocatedwithnew(a); //Returns true
allocatedwithmalloc(b); //Return true
为什么不试试计数器?
据我理解你的代码看起来是这样的:
if(ConditionA) {
A obj = new A;
} else {
A obj = malloc(sizeof(int));
}
你可以做这样的事情:
#include <iostream>
#include <stdlib.h>
using namespace std;
struct A{
int ab;
bool createdByNew;
};
int main()
{
int CountNewAllocations=0;
int CountMallocAllocations=0;
bool Condition=true; // this will be set to appropriate value
A *obj = NULL;
if(Condition) {
obj = new A;
obj->createdByNew=true;
CountNewAllocations++;
} else {
obj = (A*) malloc(sizeof(A));
obj->createdByNew=false;
CountMallocAllocations++;
}
// ... use the object
if(obj!=NULL) {
if(obj->createdByNew) {
delete obj;
CountNewAllocations--;
} else {
free(obj);
CountMallocAllocations--;
}
}
return 0;
}
'A obj3 = malloc(sizeof(int));'不会编译。所以可能会选择一个更好的例子。用malloc创建对象(不仅仅是存储)是UB,因为构造函数不会被调用。 –
不,没有。解决这个问题的最佳方法是始终使用'new',使它像魔术般消失。 – molbdnilo
清除XY问题。 VTC。 – SergeyA