Warum versuchst du es nicht mit Zählern?
Soweit ich Ihren Code verstehen sieht wie folgt aus:
if(ConditionA) {
A obj = new A;
} else {
A obj = malloc(sizeof(int));
}
Sie so etwas tun könnte:
#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));' wird nicht kompilieren. Also vielleicht ein besseres Beispiel aussuchen. Das Erstellen von Objekten (nicht nur Speicher) mit malloc ist UB, da die Konstruktoren nicht aufgerufen werden. –
Nein, gibt es nicht. Die beste Lösung für dieses Problem ist, immer "neu" zu verwenden, damit es wie durch Zauberei verschwindet. – molbdnilo
Klarer Fall von XY-Problem. VTC. – SergeyA