Is there functionality, in C++, to detect whether the target of a pointer has been allocated from dynamic memory or is living in static memory (including global memory)?
In the example below, I'd like to have the Destruction function only call delete if the target of the pointer resides in dynamic memory. (This is a minimized version of the actual code.)
#include <iostream>
using std::cout;
void Destruction(int * p_variable)
{
// The statement below should only be executed
// if p_variable points to an object in dynamic memory.
delete p_variable;
}
int main()
{
cout << "Deletion test.\n";
static int static_integer = 5;
int * p_dynamic_integer = new int;
*p_dynamic_integer = 42;
// This call will pass
Destruction(p_dynamic_integer);
int * p_static_integer = &static_integer;
// Undefined behavior???
Destruction(p_static_integer);
cout << "\nPaused. Press Enter to continue.\n";
cout.ignore(10000, '\n');
return 0;
}
The basis of the question is that I'm getting an exception error in the Destruction function because the pointer is pointing to a static integer.
The design is that a Factory Pattern function returns a pointer to a base class. The pointer could be pointing to a child that is a singleton (static memory) or an child instance from dynamic memory. A function is called to close the program (think closure of a GUI) and if the target of the pointer is from dynamic memory, it needs to be deleted.
I'm looking for a solution where I don't have to worry about deleting or not deleting the target of the pointer.
thread_locals?). Can't you return a smart pointer from the factories that also carry aboolin them that signals whether it's owned or not?std::shared_ptrfor this purpose too, if you want. Or you can have a registry of static objects and you check if the object's address is in that registry. You really can implement this however you want, but you do have to do it.