检测动态分配的对象? [英] Detect dynamically allocated object?

查看:82
本文介绍了检测动态分配的对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以检查是否动态分配了一个对象(由指针或引用传递)?

Can I check if an object (passed by pointer or reference) is dynamically allocated?

例如:

T t;
T* pt = new T();
is_tmp(&t); // false
is_tmp(pt); // true



上下文



实现这个气味像糟糕的设计,事实上是,但我试图扩展代码我不能(或应该不)修改(当然我责怪代码不是我的; ))。它调用一个方法(我可以覆盖),它将 delete 传递的对象以及其他只适用于动态分配的对象。现在,我想检查是否有可以删除 d或者它是临时的。

Context

I perfectly realise this smells like bad design, and as a matter of fact it is, but I am trying to extend code I cannot (or should not) modify (of course I blame code that isn't mine ;) ). It calls a method (which I can override) that will delete the passed object among other things that are only applicable to dynamically allocated objects. Now, I want to check whether I have something that is okay to be deleted or if it is a temporary.

我永远不会传递全局(或静态)变量,所以我在这里留下这个未定义。

I will never pass a global (or static) variable, so I leave this undefined, here.

推荐答案

在Solaris或Linux上的PC(至少32位Linux)上,
堆栈位于可用内存的最顶端,因此可以将传入的
地址与局部变量的地址进行比较:如果传入的地址
高于局部变量的地址,则
指向的对象是局部变量或临时变量,或者是
局部变量或临时变量的一部分。然而,这种技术调用了未定义的
行为,而且只是刚刚在我提到的两个
平台上工作(并且可能适用于所有平台,其中
堆栈在顶部的可用内存并增长)。

Not portably. Under Solaris or Linux on a PC (at least 32 bit Linux), the stack is at the very top of available memory, so you can compare the address passed in to the address of a local variable: if the address passed in is higher than that of the local variable, the object it points to is either a local variable or a temporary, or a part of a local variable or temporary. This technique, however, invokes undefined behavior right and left—it just happens to work on the two platforms I mention (and will probably work on all platforms where the stack is at the top of available memory and grows down).

FWIW:您还可以检查这些机器上的静态。所有静态数据在内存底部是
,链接器在
末尾插入一个符号 end 。因此,用这个名称
声明一个外部数据(任何类型),并比较它的地址。

FWIW: you can also check for statics on these machines. All statics are at the bottom of memory, and the linker inserts a symbol end at the end of them. So declare an external data (of any type) with this name, and compare the address with it.

然而关于可能删除对象。 ..只知道
对象不在堆上(也不是静态)是不够的。
对象可能是更大的动态分配对象的成员。

With regards to possibly deleting the object, however... just knowing that the object is not on the heap (nor is a static) is not enough. The object might be a member of a larger dynamically allocated object.

这篇关于检测动态分配的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆