在 C++ 中是否有检测指针目标是从动态内存分配还是存在于静态内存(包括全局内存)中的功能?
在下面的示例中,我希望仅在指针的目标驻留在动态内存中Destruction
时才调用该函数。delete
(这是实际代码的最小化版本。)
#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;
}
问题的基础是我在Destruction
函数中遇到异常错误,因为指针指向静态整数。
设计是工厂模式函数返回一个指向基类的指针。指针可能指向作为单例(静态内存)的子对象或来自动态内存的子实例。调用一个函数来关闭程序(想想 GUI 的关闭),如果指针的目标来自动态内存,则需要将其删除。
我正在寻找一种解决方案,我不必担心删除或不删除指针的目标。